An open API service indexing awesome lists of open source software.

https://github.com/0bvim/fastapi_doc


https://github.com/0bvim/fastapi_doc

Last synced: 26 days ago
JSON representation

Awesome Lists containing this project

README

          

# FastAPI Documentation Demo

A demonstration project showcasing FastAPI's automatic API documentation generation using **Swagger UI** and **ReDoc**. This project illustrates how to create well-documented APIs with deprecated endpoints, multiple API versions, and comprehensive docstrings.

## 🎯 Purpose

This project demonstrates:
- **Automatic API Documentation**: How FastAPI generates interactive documentation
- **Swagger UI Integration**: Interactive API testing interface at `/docs`
- **ReDoc Integration**: Clean, responsive API documentation at `/redoc`
- **Endpoint Deprecation**: How to properly mark and document deprecated endpoints
- **API Versioning**: Managing multiple versions of the same endpoint
- **Rich Docstrings**: Writing comprehensive endpoint documentation

## 🚀 Quick Start

### Prerequisites

- Python 3.7+
- [uv](https://docs.astral.sh/uv/) (Fast Python package manager)

### Installing uv

If you don't have uv installed yet:

**macOS and Linux:**
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

**Windows:**
```bash
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
```

**Alternative (with pip):**
```bash
pip install uv
```

### Installation

1. **Clone or download this project**
```bash
cd fastapi
```

2. **Install dependencies using uv**
```bash
uv sync
```

Or if you don't have a `pyproject.toml`, install directly:
```bash
uv add fastapi uvicorn
```

### Running the Application

Start the development server using uv:
```bash
uv run uvicorn main:app --reload
```

The API will be available at: `http://localhost:8000`

## 📚 Accessing Documentation

Once the server is running, you can access the automatic documentation at:

### Swagger UI (Interactive)
- **URL**: http://localhost:8000/docs
- **Features**:
- Interactive API testing
- Try endpoints directly in the browser
- Automatic request/response examples
- Schema validation

### ReDoc (Clean Documentation)
- **URL**: http://localhost:8000/redoc
- **Features**:
- Clean, responsive design
- Comprehensive API overview
- Detailed schema documentation
- Better for sharing with stakeholders

### OpenAPI Schema (JSON)
- **URL**: http://localhost:8000/openapi.json
- **Purpose**: Raw OpenAPI specification for integration with other tools

## 🔍 API Endpoints

| Endpoint | Method | Status | Description |
|----------|--------|--------|-------------|
| `/` | GET | ✅ Active | Health check endpoint |
| `/v1/data` | GET | ⚠️ Deprecated | Legacy data endpoint (will be removed) |
| `/v2/data` | GET | ✅ Active | Current data endpoint |

## 🛠 How It Works

### 1. FastAPI App Configuration

```python
app = FastAPI(
title="Deprecation Demo API",
description="A simple API to demonstrate how to deprecate an endpoint.",
version="1.0.0",
)
```

The `FastAPI()` constructor accepts metadata that appears in the generated documentation:
- **title**: Main title of your API
- **description**: Overview description
- **version**: API version number

### 2. Automatic Documentation Generation

FastAPI automatically generates documentation from:
- **Function signatures**: Parameter types and return types
- **Docstrings**: Detailed endpoint descriptions
- **Type hints**: Request/response schemas
- **Pydantic models**: Data validation and serialization

### 3. Deprecation Handling

```python
@app.get("/v1/data", deprecated=True)
```

The `deprecated=True` parameter:
- Marks the endpoint as deprecated in documentation
- Shows a strikethrough in Swagger UI
- Adds deprecation warnings in ReDoc
- Helps API consumers migrate to newer versions

### 4. Rich Docstrings

```python
async def get_old_data():
"""
**This endpoint is deprecated and will be removed in a future version.**

Please use the new `/v2/data` endpoint instead.

This endpoint retrieves legacy data.
"""
```

Docstrings support:
- **Markdown formatting**: Bold, italic, links, etc.
- **Multi-line descriptions**: Detailed explanations
- **Usage instructions**: How to use the endpoint
- **Migration guidance**: For deprecated endpoints

## 🎨 Documentation Features Demonstrated

### Swagger UI Features
- **Interactive Testing**: Click "Try it out" to test endpoints
- **Request Examples**: Automatic generation of example requests
- **Response Codes**: All possible HTTP status codes
- **Schema Validation**: Real-time validation of requests

### ReDoc Features
- **Responsive Design**: Works on desktop and mobile
- **Code Samples**: Multiple programming language examples
- **Deep Linking**: Direct links to specific endpoints
- **Download Specs**: Export OpenAPI specification

### Advanced Documentation
- **Deprecation Warnings**: Visual indicators for deprecated endpoints
- **Version Management**: Clear separation between API versions
- **Error Documentation**: Comprehensive error response schemas
- **Authentication**: Support for various auth schemes (when implemented)

## 🔧 Customization Options

### Using with uv project management
If you want to use this with a full uv project setup:
```bash
uv init
uv add fastapi uvicorn
uv run uvicorn main:app --reload
```

### Custom Documentation URLs
```python
app = FastAPI(docs_url="/api/docs", redoc_url="/api/redoc")
```

### Disable Documentation (Production)
```python
app = FastAPI(docs_url=None, redoc_url=None)
```

### Custom OpenAPI Schema
```python
from fastapi.openapi.utils import get_openapi

def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="Custom API",
version="2.5.0",
description="Custom OpenAPI schema",
routes=app.routes,
)
app.openapi_schema = openapi_schema
return app.openapi_schema

app.openapi = custom_openapi
```

## 📖 Learning Resources

- [FastAPI Documentation](https://fastapi.tiangolo.com/)
- [OpenAPI Specification](https://swagger.io/specification/)
- [ReDoc Documentation](https://redoc.ly/)
- [Swagger UI Documentation](https://swagger.io/tools/swagger-ui/)

## 📦 Dependencies

This project includes a `requirements.txt` file for compatibility with traditional pip workflows, but **uv is the recommended package manager** for faster dependency resolution and installation.

## 🤝 Contributing

This is a demonstration project. Feel free to:
- Add more endpoints with different features
- Implement request/response models with Pydantic
- Add authentication examples
- Include error handling demonstrations

When contributing, please use `uv` for dependency management:
```bash
uv add
uv run
```

## 📄 License

This project is for educational purposes and is free to use and modify.