Skip to main content

Generate Class & Decorators for your FastAPI project

Project description

Fastapi-Class 🦜

codecov Downloads


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

Install the project: pip install fastapi-class


Classes and Decorators to use FastAPI with class based routing. In particular this allows you to construct an instance of a class and have methods of that instance be route handlers for FastAPI & Python 3.8.

  • Older Versions of Python:
    • Unfortunately this does not work with async routes with Python versions less than 3.8 due to bugs in inspect.iscoroutinefunction. Specifically with older versions of Python iscoroutinefunction incorrectly returns false so async routes aren't await'd. We therefore only support Python versions >= 3.8.

Example 🐢

from ping import pong
# Some fictional ping pong class
from fastapi_class import Routable, get, delete

def parse_arg() -> argparse.Namespace:
   """parse command line arguments."""
   ...


class UserRoutes(Routable):
   """Inherits from Routable."""

   # Note injection here by simply passing values to the constructor. Other injection frameworks also
   # supported as there's nothing special about this __init__ method.
   def __init__(self, pong: pong) -> None:
      """Constructor. The pong is injected here."""
      self.__pong = pong

   @get('/user/{name}')
   def get_user_by_name(name: str) -> User:
      # Use our injected pong instance.
      return self.__pong.get_user_by_name(name)

   @delete('/user/{name}')
   def delete_user(name: str) -> None:
      self.__pong.delete(name)


def main():
    args = parse_args()
    # Configure the pomg per command line arguments
    pong = pong(args.url, args.user, args.password)
    # Simple intuitive injection
    user_routes = UserRoutes(pong)

    app = FastAPI()
    # router member inherited from Routable and configured per the annotations.
    app.include_router(user_routes.router)

Why 🐣

FastAPI generally has one define routes like:

app = FastAPI()

@app.get('/echo/{x}')
def echo(x: int) -> int:
   return x

Note: that app is a global. Furthermore, FastAPI's suggested way of doing dependency injection is handy for things like pulling values out of header in the HTTP request. However, they don't work well for more standard dependency injection scenarios where we'd like to do something like inject a Data Access Object or database connection. For that, FastAPI suggests their parameterized dependencies which might look something like:

app = FastAPI()

class ValueToInject:
   def __init__(self, y: int) -> None:
      self.y = y

   def __call__(self) -> int:
      return self.y

to_add = ValueToInject(2)

@app.get('/add/{x}')
def add(x: int, y: Depends(to_add)) -> int:
   return x + y

Development 🚧

You should create a virtual environment and activate it:

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

And then install the development dependencies:

pip install -r requirements.dev.txt

Format the code 💅

Execute the following command to apply pre-commit formatting:

make lint

License 🍻

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

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_class-1.0.0.tar.gz (5.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_class-1.0.0-py3-none-any.whl (5.9 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_class-1.0.0.tar.gz.

File metadata

  • Download URL: fastapi_class-1.0.0.tar.gz
  • Upload date:
  • Size: 5.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7

File hashes

Hashes for fastapi_class-1.0.0.tar.gz
Algorithm Hash digest
SHA256 b1966ffe5b749f36d0d4685ce11898e3ae1e9f0df777cf76a12cd17adf99986f
MD5 0fd058c1fe4f5d675f159d1ee44dbe75
BLAKE2b-256 41500fa8bde4cd1589e0984ad806d2a6fd5fde9889b858c12d2b3c45f1d7267d

See more details on using hashes here.

File details

Details for the file fastapi_class-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: fastapi_class-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 5.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7

File hashes

Hashes for fastapi_class-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7a8be575199efb27e45f39ec858e72e2dc207892948b465efe3a688bdc669654
MD5 44dbf0435e37fcca89351e07e9e48af3
BLAKE2b-256 60be7f296995e06c45f5136bf43eac83c5c06f751794907e0fe619b0d7a2997c

See more details on using hashes here.

Supported by

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