All Guides

FastAPI Setup

Build fast and modern Python web APIs with FastAPI.

Intermediate15 min

Setup Steps

1. Install FastAPI and Uvicorn:

pip install fastapi uvicorn[standard]

2. Create a simple API (main.py):

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

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

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

@app.post("/items/")
def create_item(item: Item):
    return item

3. Start the server:

uvicorn main:app --reload --host 0.0.0.0 --port 8000

4. Access API documentation:

- Swagger UI: http://localhost:8000/docs

- ReDoc: http://localhost:8000/redoc

5. Async endpoint:

python
@app.get("/async-test")
async def async_endpoint():
    return {"result": "async is working"}

6. Production deployment:

uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4