Giter Site home page Giter Site logo

wu-clan / fastapi-class Goto Github PK

View Code? Open in Web Editor NEW

This project forked from yezz123/fastapi-class

0.0 0.0 0.0 159 KB

provides a class-based View decorator to help reduce the amount of boilerplate necessary when developing related routes. โœจ๐Ÿš€

License: MIT License

Shell 4.36% Python 95.64%

fastapi-class's Introduction

Class

Classes and Decorators to use FastAPI with Class based routing

Test Package version Supported Python versions


Source Code: https://github.com/yezz123/fastapi-class

Install the project: pip install fastapi-class


As you create more complex FastAPI applications, you may find yourself frequently repeating the same dependencies in multiple related endpoints.

A common question people have as they become more comfortable with FastAPI is how they can reduce the number of times they have to copy/paste the same dependency into related routes.

fastapi_class provides a class-based view decorator @View to help reduce the amount of boilerplate necessary when developing related routes.

Highly inspired by Fastapi-utils, Thanks to @dmontagu for the great work.

  • Example:
from fastapi import FastAPI, APIRouter, Query
from pydantic import BaseModel
from fastapi_class import View

app = FastAPI()
router = APIRouter()

class ItemModel(BaseModel):
    id: int
    name: str
    description: str = None

@View(router)
class ItemView:
    def post(self, item: ItemModel):
        return item

    def get(self, item_id: int = Query(..., gt=0)):
        return {"item_id": item_id}

app.include_router(router)

Response model ๐Ÿ“ฆ

Exception in list need to be either function that return fastapi.HTTPException itself. In case of a function it is required to have all of it's arguments to be optional.

from fastapi import FastAPI, APIRouter, HTTPException, status
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel

from fastapi_class import View

app = FastAPI()
router = APIRouter()

NOT_AUTHORIZED = HTTPException(401, "Not authorized.")
NOT_ALLOWED = HTTPException(405, "Method not allowed.")
NOT_FOUND = lambda item_id="item_id": HTTPException(404, f"Item with {item_id} not found.")

class ItemResponse(BaseModel):
    field: str | None = None

@view(router)
class MyView:
    exceptions = {
        "__all__": [NOT_AUTHORIZED],
        "put": [NOT_ALLOWED, NOT_FOUND]
    }

    RESPONSE_MODEL = {
        "put": ItemResponse
    }

    RESPONSE_CLASS = {
        "delete": PlainTextResponse
    }

    def get(self):
        ...

    def put(self):
        ...

    def delete(self):
        ...

app.include_router(router)

Customized Endpoints

from fastapi import FastAPI, APIRouter, HTTPException
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel

from fastapi_class import View, endpoint

app = FastAPI()
router = APIRouter()

NOT_AUTHORIZED = HTTPException(401, "Not authorized.")
NOT_ALLOWED = HTTPException(405, "Method not allowed.")
NOT_FOUND = lambda item_id="item_id": HTTPException(404, f"Item with {item_id} not found.")
EXCEPTION = HTTPException(400, "Example.")

class UserResponse(BaseModel):
    field: str | None = None

@View(router)
class MyView:
    exceptions = {
        "__all__": [NOT_AUTHORIZED],
        "put": [NOT_ALLOWED, NOT_FOUND],
        "edit": [EXCEPTION]
    }

    RESPONSE_MODEL = {
        "put": UserResponse,
        "edit": UserResponse
    }

    RESPONSE_CLASS = {
        "delete": PlainTextResponse
    }

    def get(self):
        ...

    def put(self):
        ...

    def delete(self):
        ...

    @endpoint(("PUT",), path="edit")
    def edit(self):
        ...

Note: The edit() endpoint is decorated with the @endpoint(("PUT",), path="edit") decorator, which specifies that this endpoint should handle PUT requests to the /edit path, using @endpoint("PUT", path="edit") has the same effect

Development ๐Ÿšง

Setup environment ๐Ÿ“ฆ

You should create a virtual environment and activate it:

python -m venv venv/
source venv/bin/activate

And then install the development dependencies:

# Install dependencies
pip install -e .[test,lint]

Run tests ๐ŸŒ

You can run all the tests with:

bash scripts/test.sh

Format the code ๐Ÿ‚

Execute the following command to apply pre-commit formatting:

bash scripts/format.sh

Execute the following command to apply mypy type checking:

bash scripts/lint.sh

License

This project is licensed under the terms of the MIT license.

fastapi-class's People

Contributors

dependabot[bot] avatar lgtm-com[bot] avatar wu-clan avatar yezz123 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.