Skip to main content

Generic and common response schemas for FastAPI

Project description

☄️ FastAPI Response Schema

PyPI PyPI - Python Version GitHub code size in bytes Commits TestsLint

Overview

This package extends the FastAPI response model schema allowing you to have a common response wrapper via a fastapi.routing.APIRoute.

This library supports Python versions >=3.8 and FastAPI versions >=0.89.1.

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: T
    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(
        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"
    }
}

Docs

You can find detailed info for this package in the Documentation.

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.

More info on Docs section

Contributors Wall

Contributors Wall

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_responseschema-2.1.0.tar.gz (11.0 kB view details)

Uploaded Source

Built Distribution

fastapi_responseschema-2.1.0-py3-none-any.whl (12.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_responseschema-2.1.0.tar.gz.

File metadata

  • Download URL: fastapi_responseschema-2.1.0.tar.gz
  • Upload date:
  • Size: 11.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.8.18 Linux/6.2.0-1018-azure

File hashes

Hashes for fastapi_responseschema-2.1.0.tar.gz
Algorithm Hash digest
SHA256 2948e20509235bdfed24788cdbce65be62a3af8aa4f1a0d459c4fddb78eb717f
MD5 d6807a4a0883083e351e841041a1497f
BLAKE2b-256 6dda749ac5be7149427b59c3e0c3ae1c25ebae3b7514bd585dc3085f4499d770

See more details on using hashes here.

File details

Details for the file fastapi_responseschema-2.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_responseschema-2.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dbb96f838b83323d11faababa3dc17ce760701f5d2ac6c25632935b09e65507a
MD5 ed6ca89677a9bff1623c380c53eaecdf
BLAKE2b-256 07eeab8ca40cd4b6c7c776135c8f7fdc145a7df459a86a596aafc31cb1d6d2d7

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page