---
title: "How can you create a REST API with FastAPI in Python?"  
description: "How can you create a REST API with FastAPI in Python?"  
author: "Anubhav Sharma"  
published: 2025-11-06  
updated: 2025-11-24  
canonical: https://www.mindstick.com/forum/161987/how-can-you-create-a-rest-api-with-fastapi-in-python  
category: "python"  
tags: ["python-3.4", "Python 3"]  
reading_time: 2 minutes  

---

# How can you create a REST API with FastAPI in Python?

**How can you create a REST API with FastAPI in [Python](https://www.mindstick.com/articles/75378/simple-yet-useful-tips-when-using-python)?**

## Replies

### Reply by Ravi Vishwakarma

> Creating a [REST API](https://www.mindstick.com/articles/340967/designing-a-rest-api-using-python) with **FastAPI** in Python is simple, fast, and production-ready. Below is a clean step-by-step guide.

## Step 1 — Install FastAPI & Uvicorn

```plaintext
pip install fastapi uvicorn
```

## Step 2 — Create an API file

Create a file named `main.py`:

```python
from fastapi import FastAPI

app = FastAPI()

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

@app.get("/hello/{name}")
def say_hello(name: str):
    return {"message": f"Hello, {name}"}
```

## Step 3 — Run the API server

```plaintext
uvicorn main:app --reload
```

- `main` → filename (main.py)
- `app` → FastAPI instance
- `--reload` → auto-reload on code changes (useful during development)

## Example CRUD REST API

Below is a complete example for managing **items** in memory.

```python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    in_stock: bool = True

items = {}

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

@app.get("/items/{item_id}")
def get_item(item_id: int):
    return items.get(item_id, {"error": "Item not found"})

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    items[item_id] = item
    return {"message": "Item updated", "item": item}

@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    items.pop(item_id, None)
    return {"message": "Item deleted"}
```

## Test the API

After running `uvicorn`, open your browser:

- `http://127.0.0.1:8000/docs` → FastAPI’s **Swagger UI**
- `http://127.0.0.1:8000/redoc` → Alternative documentation view

FastAPI auto-generates documentation using OpenAPI — no extra code needed.

## Adding CORS (optional — for frontend apps)

```python
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # list specific domains in production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
```

## With Database Example (SQLAlchemy)

Install DB dependencies first:

```plaintext
pip install sqlalchemy
```

Sample setup:

```python
from fastapi import FastAPI, Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(bind=engine)

app = FastAPI()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
```

This allows injecting DB sessions into your routes.

## Why FastAPI?

| Feature | Benefit |
| --- | --- |
| Very Fast | Built on ASGI + Starlette |
| Auto Docs | Swagger & ReDoc |
| Pydantic Models | Validation + Serialization |
| Async Ready | Supports `async`/`await` |
| Production Friendly | Works well with Docker, Gunicorn, Kubernetes |


---

Original Source: https://www.mindstick.com/forum/161987/how-can-you-create-a-rest-api-with-fastapi-in-python

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
