Skip to main content

Simple HTTP Client based on aiohttp with integration of pydantic

Project description

pydantic_aiohttp - Symbiosis of Pydantic and Aiohttp

PyPI version shields.io PyPI pyversions PyPI license

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())

Use as context manager

import asyncio

import pydantic

from pydantic_aiohttp import Client


class HelloWorldResponse(pydantic.BaseModel):
    hello: str


async def main():
    # Client will be closed automatically on exit from context
    async with Client("https://api.example.com") as client:
        response = await client.get("/hello", response_model=HelloWorldResponse)
    
    print(response.hello)


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())

Downloading files

import asyncio

from pydantic_aiohttp import Client


async def main():
    client = Client('https://source.unsplash.com')

    try:
        await client.download_file("/random", filepath="random.jpg")
    finally:
        await client.close()


if __name__ == '__main__':
    asyncio.run(main())

LICENSE

This project is licensed under the terms of the MIT license.

Project details


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.3.2.tar.gz (8.5 kB view details)

Uploaded Source

Built Distribution

pydantic_aiohttp-0.3.2-py3-none-any.whl (9.6 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_aiohttp-0.3.2.tar.gz.

File metadata

  • Download URL: pydantic_aiohttp-0.3.2.tar.gz
  • Upload date:
  • Size: 8.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.15 CPython/3.9.13 Linux/5.15.0-1017-azure

File hashes

Hashes for pydantic_aiohttp-0.3.2.tar.gz
Algorithm Hash digest
SHA256 11978279539383db8d070e4f1634c4dcebfebdcdc41c359e2e6340e4a534e2d2
MD5 07bb6f36921d803b0fe1bf9b70bb20a1
BLAKE2b-256 0575ef7ad139adc16a84f5c4c572f04ce6f1655d0d729cc8f1689c3e38c28119

See more details on using hashes here.

Provenance

File details

Details for the file pydantic_aiohttp-0.3.2-py3-none-any.whl.

File metadata

  • Download URL: pydantic_aiohttp-0.3.2-py3-none-any.whl
  • Upload date:
  • Size: 9.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.15 CPython/3.9.13 Linux/5.15.0-1017-azure

File hashes

Hashes for pydantic_aiohttp-0.3.2-py3-none-any.whl
Algorithm Hash digest
SHA256 dda921e934ff7c99cd0016e0079b8adc8be9e56c6937f5a52bc145f37f8b8c34
MD5 def990afae2bb091fd1bc33c2271dce9
BLAKE2b-256 3cb94ec77ebf7ae811aebe201049cb324d1537d137ebba5dd48de7cf49480fab

See more details on using hashes here.

Provenance

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page