Coder Social home page Coder Social logo

flc995 / fastapi-responseschema Goto Github PK

View Code? Open in Web Editor NEW

This project forked from acwazz/fastapi-responseschema

0.0 0.0 0.0 563 KB

☄️ Global response schemas for FastAPI

Home Page: https://acwazz.github.io/fastapi-responseschema/

License: MIT License

Python 100.00%

fastapi-responseschema's Introduction

☄️ FastAPI Response Schema

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

FastAPI Response Schema is still experimental and in active development.

Consider 1.x.x versions for Alpha and Beta stages. Stable API functionality and usage will be released from version 2.0.0.

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.66.0.

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"
    }
}

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.

Contributors Wall

Contributors Wall

fastapi-responseschema's People

Contributors

acwazz avatar flc995 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.