How to Build Your First FastAPI App – Step-by-Step

Thirdy Gayares

Thirdy Gayares

Author

In this article, I will show you how to set up a FastAPI project step by step. This guide is made for beginners who want to build modern Python APIs. By the end, you will have a working API server on your machine.

Important Note

Before starting, make sure you have Python 3.9 or higher installed on your machine. Newer versions of FastAPI no longer support very old Python versions. You can download and install Python from the official website: https://www.python.org/

1. Check Python Version

python --version

2. Create a Virtual Environment

python -m venv .venv
Create virtual environment

3. Activate Virtual Environment

On Windows:

.venv\Scripts\activate

On macOS / Linux:

source .venv/bin/activate

You will know it worked when you see the environment name at the start of your terminal prompt, like this:

Activate Virtual Environment

This means all Python packages you install (like FastAPI, Uvicorn, etc.) will now be installed inside this environment only – not system-wide.

If you don't see (.venv) in the terminal, that means the activation failed. Try again or check the path.

4. Install FastAPI and Uvicorn

pip install fastapi uvicorn

FastAPI is the framework. Uvicorn is the server that runs your app. Tip: you can also run pip install "fastapi[standard]". This installs FastAPI, Uvicorn, and other useful extras in one command.

Install FastAPI and Uvicorn

5. Create main.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}

6. Run the FastAPI App

uvicorn main:app --reload

The --reload flag restarts the server every time you save your code. Use it only during development.

FastAPI running output

7. Access FastAPI in Browser

http://127.0.0.1:8000
{
  "message": "Hello, FastAPI!"
}

8. Explore FastAPI Docs

Swagger UI:

http://127.0.0.1:8000/docs

ReDoc:

http://127.0.0.1:8000/redoc
FastAPI Swagger Docs

9. Add More Routes

Add this to main.py, below your first route:

from typing import Optional

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

q is an optional query parameter. If you do not pass it, its value will be null in the response.

Test it in browser:

http://127.0.0.1:8000/items/42?q=test
{
  "item_id": 42,
  "q": "test"
}

10. Create requirements.txt (Optional)

Save a list of your installed packages:

pip freeze > requirements.txt

Later, on another machine, install them all again with:

pip install -r requirements.txt
Do you have any comments or suggestions?