+: bash script con llamados a la api usando curl

This commit is contained in:
devfzn 2023-03-31 02:36:20 -03:00
parent 74220d57c8
commit cb4fa03a92
Signed by: devfzn
GPG Key ID: E070ECF4A754FDB1
2 changed files with 134 additions and 16 deletions

View File

@ -7,7 +7,7 @@
- Python (>=3.10)
- Django
Optional:
<details><summary markdown="span">Opcionales</summary>
- PyYAML, uritemplate: Schema generation support.
- Markdown: Markdown support for the browsable API.
@ -15,25 +15,19 @@ Optional:
- django-filter: Filtering support.
- django-guardian: Object level permissions support.
**En entorno virtual**
```py
pip install djangorestframework
```
</details></br>
### Instalacion
Instalar [requerimientos](./requirements.txt) **en entorno virtual**
```py
pip install django-extensions djangorestframework djangorestframework-jsonapi \
inflection python-dotenv sqlparse
pip install -r requirements.txt
```
Django utiliza SQLite3 por defecto para simplificar el desarrolo, en este proyecto
se utliza MariaDB, pero es opcional.
```py
pip install mysqlclient
```
se utliza MariaDB, pero es opcional. Si no requiere sacarlo de
[requirements.txt](./requirements.txt) o desinstalarlo `pip uninstall mysqlclient`
## Inicio del proyecto
@ -77,6 +71,7 @@ ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ")
```
Añadir aplicaciones
```py
INSTALLED_APPS = [
'django.contrib.admin',
@ -90,7 +85,6 @@ INSTALLED_APPS = [
'rest_framework', # <---
'core', # <---
]
```
Añadir variables del framework REST al final del arhivo.
@ -225,6 +219,7 @@ Crear las migraciones y migrar.
./manage.py makemigrations
./manage.py migrate
```
Finalmente, crear **super usuario**.
```py
@ -248,6 +243,8 @@ http post http://127.0.0.1:8000/contact/ name="DevFzn" message="prueba" \
email="devfzn@mail.com"
```
<details><summary markdown="span">httpie output</summary>
```http
HTTP/1.1 200 OK
Allow: POST, OPTIONS
@ -274,7 +271,9 @@ X-Frame-Options: DENY
}
```
Se puede utilizar la shell de Django para chequear la nueva entrada en Contacto
</details>
Se puede utilizar la shell de Django para chequear la nueva entrada en Contact
`./manage.py shell`
@ -305,6 +304,8 @@ Utilizando las clases `APIClient` que proporciona un cliente incorporado y
Correr test `./manage.py test`
<details><summary markdown="span">tests output</summary>
```py
Found 8 test(s).
Creating test database for alias 'default'...
@ -317,6 +318,8 @@ OK
Destroying test database for alias 'default'...
```
</details>
## Ecommerce endpoint
Este se compone de 2 endpoints, **items** y **order**. La primera se encarga
@ -449,6 +452,8 @@ http post http://127.0.0.1:8000/api-token-auth/ username=<tu-usuario> \
password=<tu-password>
```
<details><summary markdown="span">httpie output</summary>
```http
HTTP/1.1 200 OK
Allow: POST, OPTIONS
@ -466,6 +471,8 @@ X-Frame-Options: DENY
}
```
</details>
### Ecommerce Model
Esta app hace uso obligatorio del token de autentificación. Solo usuarios
@ -522,6 +529,8 @@ Creación de [test](./backend/ecommerce/tests.py) unitarios para la aplicación.
Correr tests `./manage.py test`.
<details><summary markdown="span">tests output</summary>
```py
Found 18 test(s).
Creating test database for alias 'default'...
@ -534,9 +543,15 @@ OK
Destroying test database for alias 'default'...
```
</details>
</br>
[Bash script](./api_calls.sh) con llamadas a la API utilizando curl
----
### Jerarquia de directorios
<details><summary markdown="span">Jerarquía de directorios</summary>
```txt
📂️ .
@ -576,7 +591,10 @@ Destroying test database for alias 'default'...
│ ├── .env
│ └── manage.py
├── .gitignore
├── api_calls.sh
├── env.template
├── README.md
└── requirements.txt
```
</details>

100
api_calls.sh Executable file
View File

@ -0,0 +1,100 @@
#!/usr/bin/env bash
#
# API Calls using curl and httpie
API_URL='http://127.0.0.1:8000'
USER="$(read -p 'Username: ' && echo ${REPLY})"
printf 'Password: '
PASS="$(read -s ; echo ${REPLY})"
TOKEN=''
while :; do
printf '\nLlamadas a API en %s\n' "${API_URL}"
read -p 'URL ok? (Y/n/q)'
case "${REPLY}" in
[yY]|[sS]|[Ss][Ii]|[Yy][Ee][Ss]|'')
break
;;
[Nn]|[Nn][Oo])
API_URL="$(read -p 'URL: ' && echo ${REPLY})"
echo
;;
[Qq])
exit 0
;;
*)
printf '\nOpción inválida [%s]\n' "${REPLY}"
;;
esac
done
TOKEN="$(curl -sX POST -F "username=${USER}" -F "password=${PASS}" \
"${API_URL}/api-token-auth/" | jq -r .'[]')"
ITEM0_ID="$(curl -sX GET -H "Authorization: Token ${TOKEN}" "${API_URL}/item/" |
jq -r '.data[-1].id')"
ODER0_ID="$(curl -sX GET -H "Authorization: Token ${TOKEN}" "${API_URL}/order/" |
jq -r '.data[-1].id')"
separator(){
echo && printf '┄%.0s' {1..90} && echo
}
api_get_token(){
separator && printf '%s\n' "${1}"
printf 'curl -X POST -F "username=%s" -F "password=%s" "%s/api-token-auth/"\n' \
"${USER}" "${PASS//*/XXXX}"
curl -sX POST -F "username=${USER}" -F "password=${PASS}" \
"${API_URL}/api-token-auth/" | jq
}
api_item_call(){
separator
printf '%s\n' "${1}"
printf 'curl -X GET -H "Authorization: Token %s"\n\t\t\b"%s/%s"\n' "${TOKEN}" \
"${API_URL}" "${2}"
curl -sX GET -H "Authorization: Token ${TOKEN}" "${API_URL}/${2}" | jq
}
api_order_call(){
separator
printf '%s\n' "${1}"
printf 'curl -X POST -H "Content-Type: application/json" \ \n'
printf ' -H "Authorization: Token %s" \ \n' "${TOKEN}"
printf ' -d "{"item": "%s", "quantity": "%s"} \ \n' "${3}" "${4}"
printf ' %s/order/\n' "${API_URL}"
curl -sX POST -H 'Content-Type: application/json' \
-H "Authorization: Token ${TOKEN}" \
-d "{\"item\": \"${ITEM0_ID}\", \"quantity\": \"${4}\"}" \
"${API_URL}/${2}" | jq
}
api_getorder_call(){
separator
printf '%s\n' "${1}"
printf 'curl -X GET -H "Authorization: Token %s"\n %s/%s' \
"${TOKEN}" "${API_URL}" "${2}"
curl -sX GET -H "Authorization: Token ${TOKEN}" "${API_URL}/${2}" | jq
}
api_contact_call(){
separator
printf '%s\n' "${1}"
printf 'curl -X POST -H "Content-type: application/json" \ \n'
printf ' -d "{"name": "%s", "message": "%s", "email":"%s"}"\n' \
"${2}" "${3}" "${4}"
printf ' %s/contact/\n' "${API_URL}"
curl -sX POST -H "Content-type: application/json" \
-d "{\"name\": \"${2}\", \"message\": \"${3}\", \"email\":\"${4}\"}" \
"${API_URL}/contact/" | jq
}
api_get_token "1) Devuelve el token"
api_item_call "2) Devuelve todos los items" "item/"
api_item_call "3) Devuelve el primer item" "item/${ITEM0_ID}/"
api_order_call "4) Realiza un pedido" "order/" "${ITEM0_ID}" 1
api_getorder_call "5) Devuelve todas las ordenes" "order/"
api_getorder_call "6) Devuelve la primera orden" "order/${ODER0_ID}/"
api_contact_call "7) Crea un contacto" "DevFzn" "test contacto" "devfzn@mail.com"
exit 0