Github - QuickApiClient: Create fully typed and declarative API clients easily
(github.com)
from martinn@programming.dev to python@programming.dev on 22 Sep 2024 10:09
https://programming.dev/post/19709171
from martinn@programming.dev to python@programming.dev on 22 Sep 2024 10:09
https://programming.dev/post/19709171
A library for creating fully typed and declarative API clients, quickly and easily.
What would an API client with this library look like?
For a single API endpoint over HTTP GET, it could look something like this:
from dataclasses import dataclass import quickapi # An example type that will be part of the API response @dataclass class Fact: fact: str length: int # What the API response should look like @dataclass class ResponseBody: current_page: int data: list[Fact] # Now we can define our API class MyApi(quickapi.BaseApi[ResponseBody]): url = "https://catfact.ninja/facts" response_body = ResponseBody
And you would use it like this:
response = MyApi().execute() # That's it! Now `response` is fully typed (including IDE support) and conforms to our `ResponseBody` definition assert isinstance(response.body, ResponseBody) assert isinstance(response.body.data[0], Fact)
It also supports attrs
or pydantic
(or dataclasses
as above) for your model/type definitions, including validation and types/data conversion.
I have a lot more examples (e.g. POST requests, query string params, authentication, error handling, model validation and conversion, multiple API endpoints) on the repo’s README.
I’ve shared this one here before but it’s been a while and I’ve added a lot of features since.
Github repo: github.com/martinn/quickapiclient
#python
threaded - newest