Saltar a contenido

JSON

Definimos la url a donde se enviarán o recibirán los datos.

1
2
3
4
5
6
7
from app.common.http.rest import ClientApi
from typing import Optional, Any
...

BASE_URL = "https://httpbin.org/post"
headers: dict[str, Any] = {"Authorization": "Bearer: AWESOME_TOKEN_HERE"}
body: dict[str, Any] = {"ola": "ke ase"}

creamos la instancia de ClientApi

api = ClientApi()
api.set_headers(headers)

realizamos la petición

result: Optional[dict[str, Any]] = api.post(BASE_URL, body)

manejando los resultados

if result is None:
    logger.warning("client api: no response was obtained from the service...")
    return None

match result.get("status"):
    case 200 | 201:
        ...

        resp: Any = result.get("data", None)
        logger.info("client api: default response: {}", resp)
    case 401:
        ...

        error = result.get("data", None)
        logger.warning("client api error 401: {}", error)
    case _:
        ...

        error = result.get("data", None)
        logger.warning("client api error: {}", error)
        logger.warning("client api: an error occurred with the service response (http status)")

return None

Nota

ClientApi fija de manera predeterminada las cabeceras Content-Type: application/json

Lectura recomendada