Generic and common response schemas for FastAPI
Project description
☄️ FastAPI Response Schema
Overview
This package extends the FastAPI response model schema allowing you to have a common response wrapper via a fastapi.routing.APIRoute
.
Getting started
Install the package
pip install fastapi-responseschema
If you are planning to use the pagination integration, you can install the package including fastapi-pagination
pip install fastapi-responseschema[pagination]
Usage
from typing import Generic, TypeVar, Any, Optional, List
from pydantic import BaseModel
from fastapi import FastAPI
from fastapi_responseschema import AbstractResponseSchema, SchemaAPIRoute, wrap_app_responses
# Build your "Response Schema"
class ResponseMetadata(BaseModel):
error: bool
message: Optional[str]
T = TypeVar("T")
class ResponseSchema(AbstractResponseSchema[T], Generic[T]):
data: Any
meta: ResponseMetadata
@classmethod
def from_exception(cls, reason, status_code, message: str = "Error", **others):
return cls(
data=reason,
meta=ResponseMetadata(error=status_code >= 400, message=message)
)
@classmethod
def from_api_route_params(
cls, content: Any, status_code: int, description: Optional[str] = None, **others
):
return cls(
data=content,
meta=ResponseMetadata(error=status_code >= 400, message=description)
)
# Create an APIRoute
class Route(SchemaAPIRoute):
response_schema = ResponseSchema
# Integrate in FastAPI app
app = FastAPI()
wrap_app_responses(app, Route)
class Item(BaseModel):
id: int
name: str
@app.get("/items", response_model=List[Item], description="This is a route")
def get_operation():
return [Item(id=1, name="ciao"), Item(id=2, name="hola"), Item(id=3, name="hello")]
Te result of GET /items
:
HTTP/1.1 200 OK
content-length: 131
content-type: application/json
{
"data": [
{
"id": 1,
"name": "ciao"
},
{
"id": 2,
"name": "hola"
},
{
"id": 3,
"name": "hello"
}
],
"meta": {
"error": false,
"message": "This is a route"
}
}
Contributing
Contributions are very welcome!
How to contribute
Just open an issue or submit a pull request on GitHub.
While submitting a pull request describe what changes have been made.
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
Close
Hashes for fastapi-responseschema-1.2.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 61aa22b78ecbfa32a5ff45ace229a28f0d6d29ba1892b6412d4efa48198c2552 |
|
MD5 | 2d15986a292d77b94551c542e044528d |
|
BLAKE2b-256 | 5f90b6b7b595a85a5d641c4ac2bd73ffce387498ace8faef57346ee2fe9053dc |
Close
Hashes for fastapi_responseschema-1.2.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | c93ad9c596d7c6892681a6dfd0daa515beb04a80f4217b416f6ecf00cabf4df8 |
|
MD5 | 2b20da227de1c678d490c8f8ba617171 |
|
BLAKE2b-256 | 8a291baa621f2f18ec247f7512292f37bc2cc41286bac516abdec6c04606ccde |