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=0, name="ciao"), Item(id=1, name="hola"), Item(id=1, name="hello")]
Te result of GET /items
:
HTTP/1.1 200 OK
content-length: 131
content-type: application/json
{
"data": [
{
"id": 0,
"name": "ciao"
},
{
"id": 1,
"name": "hola"
},
{
"id": 1,
"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.0.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 377a900c9754be3c3229c3e69dfd7ce72e59810f2fd000315cd4d0544666795a |
|
MD5 | a12bbd6fe84505e36b8575336d406862 |
|
BLAKE2b-256 | 3e78fa6362e3d5898bc509e7c4d2f84654b0623ebbf5b71735e0a417094357d3 |
Close
Hashes for fastapi_responseschema-1.0.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | d30e1da2d738bb61a411a71db55bc3472a86267b1a22ddc3ba2786c879193493 |
|
MD5 | 07eaee1f72aadf20f1d0596ad4f16907 |
|
BLAKE2b-256 | e6d00aee7973dc0512219621df8665361e83e567a10284efe4c5f024d171320b |