Installation & First App¶
Let's install FastAPI and run a "Hello, World!" server in 5 minutes.
Install Python (if you don't have it)¶
You need Python 3.10+. Check with:
If missing, download from python.org.
Create a project folder¶
Create a virtual environment (recommended)¶
A virtual environment is a private Python install just for this project. Keeps your global Python clean.
# Mac / Linux
python3 -m venv .venv
source .venv/bin/activate
# Windows
python -m venv .venv
.venv\Scripts\activate
Your terminal prompt will now show (.venv) — that means it's active.
Install FastAPI + uvicorn¶
- fastapi — the framework (handles routing, validation, docs).
- uvicorn — the server that actually runs FastAPI. Without uvicorn, FastAPI is just Python code with nothing listening on a port.
Write your first app¶
Create a file called main.py:
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello, World!"}
That's a complete API. Three things to notice:
app = FastAPI()— creates the application instance.@app.get("/")— tells FastAPI "when someone makes a GET request to/, call the function below."- The function returns a dict — FastAPI converts it to JSON automatically.
Run the server¶
In the terminal:
You'll see:
INFO: Uvicorn running on http://127.0.0.1:8000
INFO: Started reloader process
INFO: Started server process
INFO: Application startup complete.
Now open http://127.0.0.1:8000 in your browser:
✅ Your first API is live.
What does each part of the command do?¶
uvicorn main:app --reload
│ │ │ │
│ │ │ └─ auto-restart when you edit the file
│ │ └─ the name of the FastAPI() instance inside main.py
│ └─ the Python file (main.py — without the .py)
└─ the web server
--reload is for development only. Don't use it in production — it adds overhead and watches files needlessly.
Auto-generated docs — the killer feature¶
FastAPI builds two interactive doc pages from your code automatically.
Open http://127.0.0.1:8000/docs — Swagger UI. Try the endpoint:
- Click the green GET / row.
- Click Try it out.
- Click Execute.
- See the actual response below.
Open http://127.0.0.1:8000/redoc — alternative ReDoc UI.
These docs update automatically whenever you change your code.
Add a second endpoint¶
Edit main.py:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello, World!"}
@app.get("/about")
def about():
return {
"service": "My First API",
"version": "1.0.0",
"author": "Alice"
}
Save. uvicorn auto-reloads (you'll see it in the terminal). Now hit:
- http://127.0.0.1:8000/about
- http://127.0.0.1:8000/docs — the second endpoint appears automatically
How the execution flows¶
When you visit http://127.0.0.1:8000/about:
- Your browser sends an HTTP GET request.
- uvicorn (port 8000) receives the bytes.
- uvicorn hands the request to FastAPI.
- FastAPI looks at the URL
/about, finds the matching route. - It calls
about()— your function. - The function returns a Python dict.
- FastAPI serializes the dict to JSON.
- uvicorn sends the JSON response back to your browser.
- Your browser displays the JSON.
All of that happens in milliseconds.
Common pitfalls¶
- ❗
uvicorn: command not found— your virtual environment isn't activated, or you didn't install uvicorn. Re-runpip install uvicorn. - ❗
ModuleNotFoundError: No module named 'fastapi'—pip install fastapi. - ❗
Address already in use— port 8000 is taken. Either kill the other process or run on a different port:uvicorn main:app --port 8001. - ❗ Server doesn't reload after edits — you forgot
--reload. - ❗ Code change → 500 error — check the terminal. Your code probably has a Python error. Fix it and save again.
Stop the server¶
In the terminal, press Ctrl + C.
What's next¶
Practice¶
What does this print?
Expected: True
Use uvicorn main:app --reload (not python main.py) to run the dev server
Expected: True
Quiz — Quick check¶
What you remember
Q1. What server runs FastAPI?
- Built-in
- An ASGI server like uvicorn, hypercorn, or daphne
- WSGI servers (gunicorn alone)
- Nginx
Why: FastAPI is ASGI (async). uvicorn is the most common dev/production server. For production, run uvicorn behind a process manager like gunicorn with uvicorn workers.
Q2. What does @app.get("/") do?
- Registers the decorated function as the handler for
GET / - Runs the function immediately
- Creates a database row
- Adds logging
Why: Decorator pattern. FastAPI builds a routing table at startup; the decorator tells it "this function handles GET /". Other methods:
@app.post,.put,.delete,.patch.
Q3. Where can you see auto-generated API docs?
-
/docs(Swagger UI) and/redoc(ReDoc) -
/api -
/swagger -
/openapi
Why: FastAPI auto-generates an OpenAPI spec from your route annotations. Both
/docsand/redocrender it interactively./openapi.jsonreturns the raw spec.
Common doubts¶
What's the difference between uvicorn main:app and python main.py?
python main.py runs the file as a script — without uvicorn.run() inside, nothing happens. uvicorn main:app tells uvicorn to import your module, find app, and serve it. The latter is the idiomatic dev command (with --reload for hot reload).
Do I need both fastapi and uvicorn installed?
Yes, separately. FastAPI provides the framework; uvicorn provides the server. Install via pip install "fastapi[standard]" to get both (and uvicorn[standard] for fast performance with httptools and websockets).
What's --reload and should I use it in production?
--reload restarts the server when source files change — essential in dev. Never use it in production — it adds overhead and can cause issues with workers. For production: uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4 behind a load balancer.