Step-by-Step Tutorial on Creating Your First FastAPI Project

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to make it easy to build APIs quickly and efficiently. This tutorial

Written by: Leo Nguyen

Published on: January 7, 2026

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to make it easy to build APIs quickly and efficiently. This tutorial will walk you through creating your first FastAPI project step by step.

Prerequisites

Before diving into FastAPI, ensure that you have the following prerequisites:

  • Python 3.7 or higher installed on your machine.
  • Basic knowledge of Python programming and REST API concepts.
  • An IDE or text editor (e.g., Visual Studio Code, PyCharm, etc.).
  • Familiarity with terminal/command prompt navigation.

Step 1: Set Up Your Development Environment

First, set up a virtual environment for your FastAPI project. This step is crucial to avoid package conflicts.

  1. Create a project directory:

    mkdir fastapi_project
    cd fastapi_project
  2. Set up a virtual environment:
    Use venv to create a virtual environment:

    python -m venv venv
  3. Activate the virtual environment:

    • On Windows:
      venvScriptsactivate
    • On macOS/Linux:
      source venv/bin/activate

Step 2: Install FastAPI and Uvicorn

FastAPI is a framework, and Uvicorn is the ASGI server that will run your application.

  1. Install FastAPI and Uvicorn:
    Run the following command in your terminal:

    pip install fastapi uvicorn

Step 3: Create Your First FastAPI Application

Now, it’s time to create your first FastAPI application.

  1. Create a new Python file:
    Within your project directory, create a new file named main.py:

    touch main.py
  2. Write a simple FastAPI application:
    Open main.py and add the following code:

    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    async def read_root():
        return {"Hello": "World"}
    
    @app.get("/items/{item_id}")
    async def read_item(item_id: int, q: str = None):
        return {"item_id": item_id, "q": q}

Step 4: Run Your FastAPI Application

To run your FastAPI application, use Uvicorn.

  1. Run the application:
    Execute the following command in your terminal:

    uvicorn main:app --reload
  2. Access your application:
    Open your web browser and go to http://127.0.0.1:8000. You should see:

    {"Hello": "World"}
  3. Access the auto-generated documentation:
    FastAPI automatically generates documentation for your API based on your code. Visit http://127.0.0.1:8000/docs to view the Swagger UI, where you can test your API.

Step 5: Handle Query Parameters and Path Parameters

Your FastAPI application can handle both query parameters and path parameters seamlessly. Let’s add more complexity to our application by using these parameters.

  1. Modify the main.py file:
    Update the read_item function to handle a query parameter q. This is already done in the previous step, but for clarity, here’s the relevant code again:

    @app.get("/items/{item_id}")
    async def read_item(item_id: int, q: str = None):
        return {"item_id": item_id, "q": q}
  2. Test the query parameters:
    Visit:

    http://127.0.0.1:8000/items/5?q=somequery

    You should receive a response like:

    {"item_id": 5, "q": "somequery"}

Step 6: Create a POST Endpoint

FastAPI allows you to create endpoints that can accept data via HTTP POST requests. Let’s create a simple endpoint to accept data.

  1. Add a POST endpoint:
    Update main.py to include a POST endpoint:

    from pydantic import BaseModel
    
    class Item(BaseModel):
        name: str
        price: float
        is_offer: bool = None
    
    @app.post("/items/")
    async def create_item(item: Item):
        return {"item_name": item.name, "item_price": item.price, "is_offer": item.is_offer}
  2. Test the POST endpoint:
    Use a tool like Postman or curl to send a POST request with JSON data.
    Example curl command:

    curl -X 'POST' 
      'http://127.0.0.1:8000/items/' 
      -H 'accept: application/json' 
      -H 'Content-Type: application/json' 
      -d '{
      "name": "Sample Item",
      "price": 25.5,
      "is_offer": true
    }'

    You should receive a response like:

    {"item_name": "Sample Item", "item_price": 25.5, "is_offer": true}

Step 7: Adding Validation with Pydantic

FastAPI uses Pydantic for data validation. This ensures that the incoming data is valid before it is processed.

  1. Define a Pydantic model:
    The Item class used previously serves as a Pydantic model. The type hints indicate the expected data types of the input.

  2. Error handling:
    If you test your POST endpoint with incorrect data (e.g., sending a string where a float is expected), FastAPI will automatically return a 422 Unprocessable Entity response with detailed error messages.

Step 8: Adding Middleware

You may want to add middleware for various purposes, such as logging or handling CORS.

  1. Adding CORSMiddleware:
    Modify your main.py file to include CORS support:

    from fastapi.middleware.cors import CORSMiddleware
    
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # Allows all origins
        allow_credentials=True,
        allow_methods=["*"],  # Allows all methods
        allow_headers=["*"],  # Allows all headers
    )
  2. Test for CORS:
    You can now test your API from a different origin without triggering CORS errors.

Step 9: Creating Additional Routes

As your application grows, you will likely need to create more routes. Consider organizing your routes in a structured manner.

  1. Creating routers:
    Create a new directory called routers, and then create a file items.py within it:

    mkdir routers
    touch routers/items.py
  2. Define your routes in items.py:

    from fastapi import APIRouter
    from pydantic import BaseModel
    
    router = APIRouter()
    
    class Item(BaseModel):
        name: str
        price: float
        is_offer: bool = None
    
    @router.post("/items/")
    async def create_item(item: Item):
        return {"item_name": item.name, "item_price": item.price, "is_offer": item.is_offer}
  3. Include the router in your main app:
    In main.py, import and include the router:

    from routers.items import router as items_router
    
    app.include_router(items_router)

Step 10: Testing Your FastAPI Application

FastAPI provides a robust testing framework as part of its package.

  1. Create a tests folder:

    mkdir tests
    touch tests/test_main.py
  2. Write tests:
    Use the httpx library for making requests in your tests. Install httpx:

    pip install httpx
  3. Example test code:
    Here’s an example test file test_main.py:

    from fastapi.testclient import TestClient
    from main import app
    
    client = TestClient(app)
    
    def test_read_root():
        response = client.get("/")
        assert response.status_code == 200
        assert response.json() == {"Hello": "World"}
    
    def test_create_item():
        response = client.post("/items/", json={"name": "Test", "price": 10.0})
        assert response.status_code == 200
        assert response.json() == {"item_name": "Test", "item_price": 10.0, "is_offer": None}
  4. Run the tests:
    Execute the tests using:

    pytest tests

Step 11: Deploying Your FastAPI Application

Once your application is tested and ready, you can deploy it using various cloud platforms like AWS, Google Cloud, or Heroku. Here are some general steps for deploying:

  1. Containerization:
    Use Docker to containerize your FastAPI application.

  2. Deployment:
    Choose an appropriate service to deploy your container:

    • Docker: For local tests and private servers.
    • Heroku: For easy deployments without managing servers.
  3. Dockerfile Example:
    Here’s a simple example of a Dockerfile:

    FROM python:3.9
    
    WORKDIR /app
    
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    
    COPY . .
    
    CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
  4. Build and run:
    Build your image:

    docker build -t fastapi_app .

    Run the container:

    docker run -d -p 80:80 fastapi_app

Final Note

Creating a FastAPI application is a straightforward process that leverages modern Python features. By following the steps outlined in this tutorial, you should now have a basic FastAPI application capable of handling GET and POST requests, as well as a foundation for further development and deployment. Happy coding!

Leave a Comment

Previous

Mastering Python ABCs for Interface Definition

Next

Python developer salary insights: San Francisco compared to remote opportunities