Last modified: Dec 01, 2025 By Alexander Williams

FastAPI Tutorial: Build Your First Python REST API

FastAPI is a modern Python web framework. It is fast and easy to use. This tutorial will guide you through building your first API.

You will create a simple book catalog API. This is perfect for beginners. We will cover all the essential steps.

What is FastAPI?

FastAPI is a high-performance web framework. It is used for building APIs with Python. It leverages standard Python type hints.

It provides automatic data validation. It also generates interactive API documentation. This makes development very efficient.

It is one of the fastest Python frameworks available. It is comparable to Node.js and Go in speed.

Prerequisites

You need Python 3.7 or higher installed. Basic knowledge of Python is helpful. You should also understand REST concepts.

Ensure you have pip, Python's package installer. You can check your Python version in the terminal.


python --version
    

Setting Up Your Environment

First, you need to install FastAPI. You also need an ASGI server. We will use Uvicorn for this tutorial.

Open your terminal or command prompt. Create a new directory for your project. Then, install the required packages.

For a detailed installation guide, see How to Install FastAPI in Python.


pip install fastapi uvicorn
    

If you encounter an import error later, you might need to troubleshoot. Check our guide on Fix Python ImportError: No Module Named FastAPI.

Creating Your First FastAPI Application

Create a new Python file. Name it main.py. This will be the entry point for your API.

First, import the FastAPI class. Then, create an instance of it. This instance is your application.


# Import the FastAPI class
from fastapi import FastAPI

# Create an instance of the FastAPI application
app = FastAPI()
    

Defining Your First Route

A route is a URL path that triggers a function. We use decorators to define routes. The @app.get("/") decorator creates a GET route.

Let's create a simple root endpoint. It will return a welcome message.


@app.get("/")
def read_root():
    return {"message": "Welcome to the Book API"}
    

The function read_root is the path operation function. It runs when someone visits the root URL.

Running the Development Server

To run your application, use Uvicorn. Open your terminal in the project directory. Execute the following command.


uvicorn main:app --reload
    

The --reload flag enables auto-reload. It restarts the server on code changes. This is great for development.

You should see output indicating the server is running. It typically runs on http://127.0.0.1:8000.

Testing Your API Endpoint

Open your web browser. Go to http://127.0.0.1:8000. You should see the JSON response.

You can also use command-line tools like curl. Or use API clients like Postman or Thunder Client.


curl http://127.0.0.1:8000
    

{"message":"Welcome to the Book API"}
    

Adding a Path Parameter

Path parameters let you capture values from the URL. They are defined in the path using curly braces.

Let's create an endpoint to get a book by its ID. The ID will be an integer path parameter.


@app.get("/books/{book_id}")
def read_book(book_id: int):
    # For now, return a dummy book
    return {"book_id": book_id, "title": "Sample Book"}
    

FastAPI automatically converts the path parameter. It also validates the data type. If you pass a string, it will error.

Test it by visiting http://127.0.0.1:8000/books/42.

Using Pydantic for Data Models

Pydantic is integrated with FastAPI. It provides data validation using Python type annotations.

Define a Pydantic model for your book data. This model will validate incoming and outgoing data.


from pydantic import BaseModel

# Define a Book model
class Book(BaseModel):
    id: int
    title: str
    author: str
    year: int
    

Creating a POST Endpoint

POST endpoints are used to create new resources. The request body contains the data.

Use the Book model as a parameter type. FastAPI will read the JSON body and validate it.


# In-memory "database" list
books_db = []

@app.post("/books/")
def create_book(book: Book):
    books_db.append(book)
    return book
    

The function create_book receives a validated Book object. It adds it to the list and returns it.

Automatic Interactive API Docs

One of FastAPI's best features is automatic docs. It creates Swagger UI and ReDoc interfaces.

Go to http://127.0.0.1:8000/docs. You will see Swagger UI. It lists all your API endpoints.

You can test your POST endpoint directly from the browser. Try adding a new book with the "Try it out" button.

ReDoc is available at http://127.0.0.1:8000/redoc. It provides alternative documentation.

Adding Query Parameters

Query parameters are optional key-value pairs in the URL. They are defined as function parameters.

Let's add a GET endpoint to list books. It will support optional filtering by author.


@app.get("/books/")
def list_books(author: str = None):
    if author:
        filtered_books = [b for b in books_db if b.author == author]
        return filtered_books
    return books_db
    

Test it: http://127.0.0.1:8000/books/?author=J.K.%20Rowling.

Complete Example Code

Here is the complete code for our simple book API. Copy this into your main.py file.


from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# Data Model
class Book(BaseModel):
    id: int
    title: str
    author: str
    year: int

# In-memory storage
books_db = []

@app.get("/")
def read_root():
    return {"message": "Welcome to the Book API"}

@app.get("/books/{book_id}")
def read_book(book_id: int):
    for book in books_db:
        if book.id == book_id:
            return book
    return {"error": "Book not found"}

@app.post("/books/")
def create_book(book: Book):
    books_db.append(book)
    return book

@app.get("/books/")
def list_books(author: str = None):
    if author:
        filtered_books = [b for b in books_db if b.author == author]
        return filtered_books
    return books_db
    

Next Steps and Best Practices

You have built a basic CRUD API. For real projects, use a proper database. SQLAlchemy or Tortoise-ORM are good choices.

Add error handling for missing resources. Use HTTP status codes correctly. Implement authentication and authorization.

Structure your project into modules. Use routers to organize endpoints. This keeps your code clean and scalable.

If you ever need to remove FastAPI, follow our guide on How to Uninstall FastAPI in Python.

Conclusion

FastAPI makes API development fast and fun. Its automatic validation and docs save time.

You learned to install FastAPI, define routes, use path and query parameters, and work with Pydantic models.

You built a functional book catalog API from scratch. This foundation will help you tackle more complex projects.

Keep exploring the official FastAPI documentation. It is an excellent resource for advanced features.