Overview
FastAPI is a modern, fast web framework for building APIs with Python. It can provide high performance on par with Node.js and Go.
Starlette & Uvicorn
Both Starlette and Uvicorn are essential components in the FastAPI ecosystem.
Starlette
- starlette is a lightweight ASGI (Async Server Gateway Interface) framework for building web apps
- FastAPI is built on top of starlette and pydantic, and it abstracts most of the complexity of starlette
- starlette provides core functionality for handling web requests, responses, routing, middleware and more.
Uvicorn:
- uvicorn is an ASGI server implementation, desgined to run ASGI applications, like the ones built with starlette and fastapi
- after you build your own fastapi application, you can run it with
uvicorn main:app --reload
Start FastAPI Server
To start the application:
uvicorn run demo.main:app --reload
Here, demo
is the project, main.py
is the main file and app
is an instance of FastAPI()
.
To view the Swagger.io endpoint http://127.0.0.1:8000/docs
.
Entry Point
Let’s define the main entry point of the api:
# demo/main.py
import uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World!"}
def start():
uvicorn.run("app.main:app", host="127.0.0.1", port=8000, reload=True)
API Routers
Let’s define a router:
# demo/routers/user.py
from fastapi import APIRouter
router = APIRouter()
@router.post("/parse", response_model=ParserResponse)
async def parse(req: ParserRequest):
return {"message": "parse done"}
Then include the router:
# demo/main.py
from app.routers import parser
app.include_router(parser.router)
Upload Files
Install python-multipart
, that’s a dependency.
@router.post("/parse")
async def parse(source_tempate: UploadFile = File(...), parameters: UploadFile = File(...)):
pass