DEV Community

qing
qing

Posted on

How to Build a REST API with FastAPI in 5 Minutes

How to Build a REST API with FastAPI in 5 Minutes

FastAPI is the fastest-growing Python web framework. Here is a quick tutorial to build a production-ready REST API.

Install

pip install fastapi uvicorn

Create app.py

from fastapi import FastAPI
app = FastAPI()

@app.get("/")
def root():
return {"message": "Hello World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}

Run

uvicorn app:app --reload

Visit http://localhost:8000/docs for auto-generated Swagger docs.

Add Database

Use SQLAlchemy or Tortoise ORM for database integration. FastAPI works great with async databases.

Deploy

Docker + Gunicorn + Nginx is the recommended production setup.


Start building APIs today!


More at https://青.失落.世界

Top comments (0)