FastAPI
-
Django and Flask have been the long running Python web frameworks that everyone chooses. FastAPI is a newish micro framework that allows for quick REST API development. We've been using FastAPI to write most of our microservices and it's working out pretty well. One catch is everything being asynchronous, but since FastAPI exposes a decorator for startup events, you can add them there vs manually creating tasks on the loop.
To get started it's pretty simple. Create a file named
main.py
from fastapi import FastAPI app = FastAPI() @app.get("/testing/{id}") async def get_test(id: int): data = {"id": id} return data
Then just run your app with Uvicorn:
uvicorn "main:app" --reload
--reload
adds live reloading for when you make changes.The handler methods are defined through the decorators
@app.get, @app.post, etc
. This method makes a nice quick way to define endpoints. Decorators also control startup and shutdown events and even middleware. So adding middleware to your requests is pretty trivial:@app.middleware("http") async def timer(request: Request, call_next): start = time.time() resp = await call_next(request) total_time = time.time() - start print(f'request took {total_time} seconds') return resp
So to put that all together it looks like this:
from fastapi import FastAPI, Request import time app = FastAPI() @app.middleware("http") async def timer(request: Request, call_next): start = time.time() resp = await call_next(request) total_time = time.time() - start print(f'request took {total_time} seconds') return resp @app.get("/testing/{id}") async def get_test(id: int): data = {"id": id} return data