Building a RESTful API with Python and FastAPI: A Step-by-Step Tutorial

Learn how to build a simple and efficient RESTful API using Python and FastAPI in this beginner-friendly step-by-step tutorial.

RESTful APIs allow different applications to communicate with each other over the web. FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. In this tutorial, we'll walk through building a simple RESTful API with FastAPI.

### Step 1: Install FastAPI and Uvicorn First, you need to install FastAPI and Uvicorn. Uvicorn is an ASGI server used to run FastAPI applications.

python
pip install fastapi uvicorn

### Step 2: Create a Basic FastAPI Application Create a new Python file called `main.py` and add the following code to create a simple API that responds with a greeting message.

python
from fastapi import FastAPI

app = FastAPI()

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

### Step 3: Run the Application Use Uvicorn to run your API server. Open your terminal and run:

python
uvicorn main:app --reload

Navigate to `http://127.0.0.1:8000` in your browser or send a request using a tool like Postman or curl. You should see this response:

python
{ "message": "Hello, FastAPI!" }

### Step 4: Adding Path and Query Parameters FastAPI makes it easy to receive parameters from the URL path or as query parameters. Let's modify the API to greet a user by name.

python
from fastapi import FastAPI

app = FastAPI()

@app.get("/hello/{name}")
def read_hello(name: str, age: int = 0):
    return {"message": f"Hello, {name}! Your age is {age}."}

This example uses a path parameter `name` and an optional query parameter `age`. For example, visiting `/hello/Alice?age=25` will respond with:

python
{ "message": "Hello, Alice! Your age is 25." }

### Step 5: Creating a POST Endpoint Let's create a POST endpoint where a user can send data in JSON format, and the API will return it back.

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

@app.post("/items/")
def create_item(item: Item):
    item_dict = item.dict()
    if item.tax:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
    return item_dict

You can send a POST request with JSON data like this:

python
{
    "name": "Widget",
    "description": "A useful widget",
    "price": 25.5,
    "tax": 1.5
}

The response will include the original data plus the calculated price including tax.

### Step 6: Summary In just a few lines of code, you've built a RESTful API with GET and POST endpoints using FastAPI. FastAPI automatically generates interactive API docs at `/docs` using Swagger UI, which helps you test your endpoints easily.

FastAPI is a powerful framework for building APIs quickly and efficiently while maintaining simplicity and readability. Continue exploring FastAPI's features to build more complex APIs with authentication, databases, and more!