How to Build a REST API in Python Using FastAPI

If you’re looking to build a fast, modern REST API with minimal boilerplate and great performance, FastAPI is the way to go. It’s quickly becoming the go-to framework for Python developers building APIs — and for good reason.

In this guide, you’ll learn how to build a basic REST API with Python and FastAPI, step by step.

🚀 Why Use FastAPI?

FastAPI is a high-performance web framework for building APIs with Python 3.7+. It’s built on top of Starlette and Pydantic, offering:

  • ⚡ Auto-generated Swagger docs
  • ✅ Built-in data validation with Python type hints
  • 🔒 Fast, async-ready performance
  • 🧩 Easy-to-use structure

🔧 Step 1: Install FastAPI and Uvicorn

Create a virtual environment (optional but recommended):

python -m venv venv
source venv/bin/activate  # or venv\Scripts\activate on Windows

Then install FastAPI and Uvicorn:

pip install fastapi uvicorn

📁 Step 2: Create Your First API

Create a file named main.py:

from fastapi import FastAPI

app = FastAPI()

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

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

This creates two routes:

  • / – A root welcome message
  • /items/{item_id} – A dynamic route that takes an item ID and optional query

▶️ Step 3: Run the App

Start your FastAPI server using Uvicorn:

uvicorn main:app --reload

Now go to:

✍️ Step 4: Add a POST Endpoint

Let’s add a route that accepts JSON data to demonstrate how a REST API in Python using FastAPI works :

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = False

@app.post("/items/")
def create_item(item: Item):
    return {"message": "Item created", "item": item}

Now, when you POST JSON like:

{
  "name": "Laptop",
  "price": 1499.99,
  "is_offer": true
}

You’ll get a response with the same data. FastAPI automatically validates types and shows errors for invalid input!

✅ Final Thoughts

FastAPI is a game-changer for Python developers. It combines modern syntax, blazing speed, and auto-generated documentation — all with minimal effort.

Whether you’re building a microservice, backend for a mobile app, or a full-stack project, FastAPI lets you move fast without sacrificing quality.

Start small, explore its features, and scale your API as you grow.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top