Everything else in FastAPI builds on this loop: write a function, decorate it, run the server, call the URL.
FastAPI is a Python web framework for building HTTP APIs. You write ordinary functions with type hints, and FastAPI uses those hints to parse and validate incoming data, convert your return values to JSON and generate API documentation, all from the same declaration. It stands on two libraries: Starlette does the web part (routing, requests, responses, WebSockets) and Pydantic does data validation and serialization.
FastAPI is an ASGI application, so it doesn't listen on a port by itself; an ASGI server such as Uvicorn runs it. Install it in a virtual environment with the standard extras, which bring Uvicorn, the fastapi command and common optional packages:
python -m venv .venv && source .venv/bin/activate
pip install "fastapi[standard]"Save the example as main.py and run fastapi dev main.py (plain fastapi dev also finds a main.py with an app in it). The development server starts on http://127.0.0.1:8000, watches your files and reloads on every save. Open http://127.0.0.1:8000/ and you get {"message":"Hello World"}.
For production use fastapi run main.py: no auto-reload, and it listens on 0.0.0.0 so it's reachable from outside the machine or container. Both commands wrap Uvicorn; the equivalent you'll see in older tutorials is uvicorn main:app --reload, where main:app means "the object app in module main".
Three things to notice in the code. app = FastAPI() creates the application object. @app.get("/") registers the function below it for GET requests to /. And returning a dict is enough: FastAPI turns it into a JSON response with the right Content-Type.
Example
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World"}
@app.get("/health")
def health():
return {"status": "ok"}
# $ fastapi dev main.py
# $ curl http://127.0.0.1:8000/health
# {"status":"ok"}Remember
- FastAPI = Starlette for the web layer + Pydantic for data, driven by your type hints
- pip install "fastapi[standard]" gives you Uvicorn and the fastapi command
- fastapi dev for development (auto-reload), fastapi run for production
- Returning a dict, list or model produces a JSON response
Watch out for
- Naming your own file fastapi.py: it shadows the real package and the import fails.
- Running fastapi dev (auto-reload, localhost only) in production.