Lima-API is sync and async library that allows implements Rest APIs libs with python typing.
Project description
Lima-API
Lima-API is sync and async library that allows implements Rest APIs libs with python typing.
You could read more about it on our post (Spanish).
You could install from pypi with:
pip install lima-api
Howto use it
- Create your Pydantic models.
from pydantic import BaseModel from pydantic.fields import Field class Pet(BaseModel): identifier: int = Field(alias="id") name: str
- Create your exceptions extend from
lima_api.LimaExceptionimport lima_api class PetNotFoundError(lima_api.LimaException): detail = "Pet not found" class InvalidDataMessage(BaseModel): message: str code: str class InvalidDataError(lima_api.LimaException): model = InvalidDataMessage
- Create your class extend from
lima_api.SyncLimaApiorlima_api.LimaApi.import lima_api ... class PetApi(lima_api.LimaApi): response_mapping = { 404: PetNotFoundError, }
- Create functions with the proper decorator.
import lima_api ... class PetApi(lima_api.LimaApi): ... @lima_api.get( "/pet/{petId}", response_mapping={ 400: InvalidDataError, } ) async def get_pet(self, *, petId: int) -> Pet: ...
- Create the client instance.
pet_client = PetApi("https://petstore.swagger.io/v2") async with pet_client: pet = await pet_client.get_pet(pet_id=1)
In some case you want remove APIs complexity( for example, pagination creating a private function with decorator and public one without it:
class StApi(lima_api.LimaApi):
@lima_api.get("/v1/rest/animal/search")
async def _animals_search(
self,
*,
page_number: int = lima_api.QueryParameter(alias="pageNumber"),
page_size: int = lima_api.QueryParameter(alias="pageSize", default=100),
) -> AnimalBaseResponse: ...
async def list_animals(self) -> AsyncIterator[AnimalBase]:
page_number = 0
page = await self._search(page_number=page_number)
while not page.page.lastPage:
for animal in page.animals:
yield animal
page_number += 1
page = await self._search(page_number=page_number)
for animal in page.animals:
yield animal
[!NOTE]
- Synchronous clients only support synchronous functions, and in the same way with asynchronous.
- You could see other code examples at docs/examples folder.
[!IMPORTANT]
- The Body param must be allways
BaseModelcalls and only one is valid- Functions wrapped by lima_api always must use *, in order to force use keywords for calling functions.
Parameters types
The functions parameters will mapping with the following criteria.
-
You could define the location of the param using
lima_api.LimaParameter(one of the followingslima_api.PathParameter,lima_api.QueryParameterorlima_api.BodyParameter) classes.from enum import Enum import lima_api from pydantic import BaseModel ... class PetUpdateStatus(BaseModel): name: str status: str class PetStatus(str, Enum): AVAILABLE = "available" PENDING = "pending" SOLD = "sold" class PetApi(lima_api.LimaApi): ... @lima_api.post( "/pets/{petId}", headers={"content-type": "application/x-www-form-urlencoded"}, response_mapping={405: InvalidDataError} ) async def get_update_pet( self, *, pet_id: int = lima_api.PathParameter(alias="petId"), data: PetUpdateStatus = lima_api.BodyParameter(), ) -> None: ... @lima_api.get("/pet/findByStatus") async def filter( self, *, status: list[PetStatus] = lima_api.QueryParameter(default=[]), ) -> list[Pet]: ...
-
The parameters that extend from
pydantic.BaseModelwill send to body by default except if the method isGET, in this case will send as query params.from enum import Enum import lima_api from pydantic import BaseModel ... class PetStatus(str, Enum): AVAILABLE = "available" PENDING = "pending" SOLD = "sold" class PetFilterStatus(BaseModel): status: list[PetStatus] class PetApi(lima_api.LimaApi): ... @lima_api.get("/pet/findByStatus") async def filter(self, *, status: list[PetStatus]) -> list[Pet]: ... @lima_api.get("/pet/findByStatus") async def filter_by_obj(self, *, data: PetFilterStatus) -> list[Pet]: ...
-
At the end with the regex expressed in
LimaSettings.lima_bracket_regexwill get the names in the path params and macht the param names defined in the function.For example with
lima_bracket_regex = r"\[(.+?)\]"@lima_api.get("/pets/[petId]") async def get_pet(self, *, petId: str) -> Pet: ...
Auto-start
In some case we need create a global client. In that cases maybe you don't want use with cause when you call some function. We create the kwarg auto_start that allow start and close client automatic when you call some function.
[!IMPORTANT]
- If you open and close the connection the performance could be affected.
[!NOTE]
- Synchronous clients allows use
auto_close(as False by default to have same behavior that Asynchronous has) that allow not close the connection to improve the performance.- We recommend use
within Asynchronous and in Synchronous mode withauto_start=Trueandauto_close=False.
Helps for developers
By default, lima-api don't log any information, whoever in some cases you need log information.
In order to solve this and becases the log level could be different for each case, we decide create the function def log(self, *, event: lima_api.LogEvent, **kwargs) which could be overwritten.
class PetApi(lima_api.LimaApi):
def log(self, *, event: lima_api.LogEvent, **kwargs) -> None:
if event == lima_api.LogEvent.RECEIVED_RESPONSE:
response: httpx.Response = kwargs.get("response")
logger.info(
"Request completed",
extra={
"url": response.request.url,
"elapsed": response.elapsed,
"method": response.request.method,
"service_status": response.status_code,
}
)
...
Create requirement file locally
uv pip compile pyproject.toml --extra=test --extra=pydantic2 > requirements.txt
uv pip install requirements.txt
Code generator
In order to help developers to improve they work you could auto-generate your clients.
You could run:
lima-generator tests/resources/examples/v3.0/api-with-examples.json
That create a folder tests/resources/examples/v3.0/api-with-examples with two files, client.py and models.py
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file lima_api-1.3.2.tar.gz.
File metadata
- Download URL: lima_api-1.3.2.tar.gz
- Upload date:
- Size: 43.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c09dc2fbe1c677599e1ec11acbaad6fcab4e5f0870fe8cbeddc1670b337c869c
|
|
| MD5 |
8fcdb5f4defc855d1bbe014a91f8ade2
|
|
| BLAKE2b-256 |
fd00f040fe364ef94f0dc65c118691bb9f08dd34785fb1e65710a2fdb5be5140
|
Provenance
The following attestation bundles were made for lima_api-1.3.2.tar.gz:
Publisher:
publish_package.yml on paradigmadigital/lima-api
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
lima_api-1.3.2.tar.gz -
Subject digest:
c09dc2fbe1c677599e1ec11acbaad6fcab4e5f0870fe8cbeddc1670b337c869c - Sigstore transparency entry: 152404528
- Sigstore integration time:
-
Permalink:
paradigmadigital/lima-api@d70762b83b92143a9978cf476ffab6ed6939cfc6 -
Branch / Tag:
refs/tags/1.3.2 - Owner: https://github.com/paradigmadigital
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish_package.yml@d70762b83b92143a9978cf476ffab6ed6939cfc6 -
Trigger Event:
release
-
Statement type:
File details
Details for the file lima_api-1.3.2-py3-none-any.whl.
File metadata
- Download URL: lima_api-1.3.2-py3-none-any.whl
- Upload date:
- Size: 22.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/5.1.1 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
aebfe92e77a7be3683ae7f854d3aada66a64ebe306a6a65b42c6a9bd2eab5319
|
|
| MD5 |
1ebc76f8b02851df2f12e81fa100d0d6
|
|
| BLAKE2b-256 |
fcb9e09a62dfe4a992591c50d2ace31f3843d3718c3f1de6d0a095fbf3ff531a
|
Provenance
The following attestation bundles were made for lima_api-1.3.2-py3-none-any.whl:
Publisher:
publish_package.yml on paradigmadigital/lima-api
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
lima_api-1.3.2-py3-none-any.whl -
Subject digest:
aebfe92e77a7be3683ae7f854d3aada66a64ebe306a6a65b42c6a9bd2eab5319 - Sigstore transparency entry: 152404530
- Sigstore integration time:
-
Permalink:
paradigmadigital/lima-api@d70762b83b92143a9978cf476ffab6ed6939cfc6 -
Branch / Tag:
refs/tags/1.3.2 - Owner: https://github.com/paradigmadigital
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish_package.yml@d70762b83b92143a9978cf476ffab6ed6939cfc6 -
Trigger Event:
release
-
Statement type: