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.2.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | af43bb8c73e185acd2d58a8dd6b072843d436fd70a444714c192e4be9133ff67 |
|
MD5 | 7c2ae7825941cbc5400d9e3e89306952 |
|
BLAKE2b-256 | e0cbcbc935b3025ca2fb0c8a1992269e3c55dd200b3b6de0b6fbecad113786c6 |
Close
Hashes for fastapi_responseschema-1.2.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b1ac4d5ddfccac8f5f1b85ea8cab6092e246cc5d7652e09621496b5ab4dac081 |
|
MD5 | 5984a4d7598bb4aa748314aa4d8a1640 |
|
BLAKE2b-256 | a1f7d7a07ebf98ca6ac11d0580f99ce0287a3617d821c2660b7d51b63ce51d52 |