Simple HTTP Client based on aiohttp with integration of pydantic
Project description
pydantic_aiohttp - Symbiosis of Pydantic and Aiohttp
This repository provides simple HTTP Client based on aiohttp with integration of pydantic
Examples
Basic example
import asyncio
import pydantic
from pydantic_aiohttp import Client
class HelloWorldResponse(pydantic.BaseModel):
hello: str
async def main():
example_client = Client("https://api.example.com")
response = await example_client.get("/hello", response_model=HelloWorldResponse)
print(response.hello)
# After all your work is done you should close client (this method closes aiohttp session instance)
await example_client.close()
if __name__ == '__main__':
asyncio.run(main())
Handling errors parsed as pydantic models
import http
import asyncio
import pydantic
import pydantic_aiohttp
from pydantic_aiohttp import Client
class FastAPIValidationError(pydantic.BaseModel):
loc: list[str]
msg: str
type: str
class FastAPIUnprocessableEntityError(pydantic.BaseModel):
detail: list[FastAPIValidationError]
class User(pydantic.BaseModel):
id: str
email: str
first_name: str
last_name: str
is_admin: bool
async def main():
client = Client(
"https://fastapi.example.com",
error_response_models={
http.HTTPStatus.UNPROCESSABLE_ENTITY: FastAPIUnprocessableEntityError
}
)
try:
# Imagine, that "email" field is required for this route
await client.post(
"/users",
body={
"first_name": "John",
"last_name": "Doe"
},
response_model=User
)
except pydantic_aiohttp.HTTPUnprocessableEntity as e:
# response field of exception now contain parsed pydantic model entity
print(e.response.detail[0].json(indent=4))
# >>>
# {
# "loc": [
# "body",
# "email"
# ],
# "msg": "field required",
# "type": "value_error.missing"
# }
finally:
await client.close()
if __name__ == '__main__':
asyncio.run(main())
LICENSE
This project is licensed under the terms of the MIT license.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
pydantic_aiohttp-0.2.1.tar.gz
(7.5 kB
view hashes)
Built Distribution
Close
Hashes for pydantic_aiohttp-0.2.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 011d6e0a97c5f28e8b8d2405d06c662701ca59305a741fd8b627e706a0dd0db1 |
|
MD5 | 2f726004d494b48b992dd9442272bfe2 |
|
BLAKE2b-256 | f4ce291dd71552761c31fcae0b9407f548a2d923dfe19b6340e2e390c470c321 |