Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 49 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<h1 align="center"> Fast FastAPI boilerplate</h1>
<h1 align="center"> Benav Labs FastAPI boilerplate</h1>
<p align="center" markdown=1>
<i>Yet another template to speed your FastAPI development up.</i>
</p>

<p align="center">
<a href="https://github.com/igormagalhaesr/FastAPI-boilerplate">
<img src="https://user-images.githubusercontent.com/43156212/277095260-ef5d4496-8290-4b18-99b2-0c0b5500504e.png" alt="Blue Rocket with FastAPI Logo as its window. There is a word FAST written" width="35%" height="auto">
<img src="docs/assets/FastAPI-boilerplate.png" alt="Purple Rocket with FastAPI Logo as its window." width="35%" height="auto">
</a>
</p>

Expand Down Expand Up @@ -33,6 +33,16 @@
</a>
</p>

---

## 📖 Documentation

📚 **[Visit our comprehensive documentation at benavlabs.github.io/fastapi-boilerplate](https://benavlabs.github.io/fastapi-boilerplate/)**

This README provides a quick reference for LLMs and developers, but the full documentation contains detailed guides, examples, and best practices.

---

## 0. About

**FastAPI boilerplate** creates an extendable async API using FastAPI, Pydantic V2, SQLAlchemy 2.0 and PostgreSQL:
Expand All @@ -47,7 +57,7 @@
- [`NGINX`](https://nginx.org/en/) High-performance low resource consumption web server used for Reverse Proxy and Load Balancing.

> \[!TIP\]
> If you want the `SQLModel` version instead, head to [SQLModel-boilerplate](https://github.com/igorbenav/SQLModel-boilerplate).
> There's a `SQLModel` version as well, but it's no longer updated: [SQLModel-boilerplate](https://github.com/igorbenav/SQLModel-boilerplate).

## 1. Features

Expand All @@ -62,8 +72,6 @@
- ⎘ Out of the box offset and cursor pagination support with <a href="https://github.com/igorbenav/fastcrud">fastcrud</a>
- 🛑 Rate Limiter dependency
- 👮 FastAPI docs behind authentication and hidden based on the environment
- 🦾 Easily extendable
- 🤸‍♂️ Flexible
- 🚚 Easy running with docker compose
- ⚖️ NGINX Reverse Proxy and Load Balancing

Expand Down Expand Up @@ -118,6 +126,8 @@ ______________________________________________________________________

## 3. Prerequisites

> 📖 **[See detailed installation guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/getting-started/installation/)**

### 3.0 Start

Start by using the template, and naming the repository to what you want.
Expand All @@ -144,6 +154,8 @@ git clone https://github.com/igormagalhaesr/FastAPI-boilerplate

### 3.1 Environment Variables (.env)

> 📖 **[See complete configuration guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/getting-started/configuration/)**

Then create a `.env` file inside `src` directory:

```sh
Expand Down Expand Up @@ -302,6 +314,8 @@ pip install uv

## 4. Usage

> 📖 **[See complete first run guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/getting-started/first-run/)**

### 4.1 Docker Compose

If you used docker compose, your setup is done. You just need to ensure that when you run (while in the base folder):
Expand Down Expand Up @@ -530,8 +544,12 @@ uv run alembic upgrade head

## 5. Extending

> 📖 **[See comprehensive development guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/development/)**

### 5.1 Project Structure

> 📖 **[See detailed project structure guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/project-structure/)**

First, you may want to take a look at the project structure and understand what each file is doing.

```sh
Expand Down Expand Up @@ -661,6 +679,8 @@ Note that this table is used to blacklist the `JWT` tokens (it's how you log a u

### 5.3 SQLAlchemy Models

> 📖 **[See database models guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/database/models/)**

Inside `app/models`, create a new `entity.py` for each new entity (replacing entity with the name) and define the attributes according to [SQLAlchemy 2.0 standards](https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#orm-mapping-styles):

> \[!WARNING\]
Expand All @@ -683,6 +703,8 @@ class Entity(Base):

### 5.4 Pydantic Schemas

> 📖 **[See database schemas guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/database/schemas/)**

Inside `app/schemas`, create a new `entity.py` for each new entity (replacing entity with the name) and create the schemas according to [Pydantic V2](https://docs.pydantic.dev/latest/#pydantic-examples) standards:

```python
Expand Down Expand Up @@ -731,6 +753,8 @@ class EntityDelete(BaseModel):

### 5.5 Alembic Migrations

> 📖 **[See database migrations guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/database/migrations/)**

> \[!WARNING\]
> To create the tables if you did not create the endpoints, ensure that you import the models in src/app/models/__init__.py. This step is crucial to create the new models.

Expand All @@ -748,6 +772,8 @@ uv run alembic upgrade head

### 5.6 CRUD

> 📖 **[See CRUD operations guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/database/crud/)**

Inside `app/crud`, create a new `crud_entities.py` inheriting from `FastCRUD` for each new entity:

```python
Expand Down Expand Up @@ -953,6 +979,8 @@ crud_user.get(db=db, username="myusername", schema_to_select=UserRead)

### 5.7 Routes

> 📖 **[See API endpoints guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/api/endpoints/)**

Inside `app/api/v1`, create a new `entities.py` file and create the desired routes

```python
Expand Down Expand Up @@ -993,6 +1021,8 @@ router.include_router(entity_router)

#### 5.7.1 Paginated Responses

> 📖 **[See API pagination guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/api/pagination/)**

With the `get_multi` method we get a python `dict` with full suport for pagination:

```javascript
Expand Down Expand Up @@ -1057,6 +1087,8 @@ async def read_entities(

#### 5.7.2 HTTP Exceptions

> 📖 **[See API exceptions guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/api/exceptions/)**

To add exceptions you may just import from `app/core/exceptions/http_exceptions` and optionally add a detail:

```python
Expand Down Expand Up @@ -1084,6 +1116,8 @@ if not post:

### 5.8 Caching

> 📖 **[See comprehensive caching guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/caching/)**

The `cache` decorator allows you to cache the results of FastAPI endpoint functions, enhancing response times and reducing the load on your application by storing and retrieving data in a cache.

Caching the response of an endpoint is really simple, just apply the `cache` decorator to the endpoint function.
Expand Down Expand Up @@ -1247,6 +1281,8 @@ For `client-side caching`, all you have to do is let the `Settings` class define

### 5.10 ARQ Job Queues

> 📖 **[See background tasks guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/background-tasks/)**

Depending on the problem your API is solving, you might want to implement a job queue. A job queue allows you to run tasks in the background, and is usually aimed at functions that require longer run times and don't directly impact user response in your frontend. As a rule of thumb, if a task takes more than 2 seconds to run, can be executed asynchronously, and its result is not needed for the next step of the user's interaction, then it is a good candidate for the job queue.

> [!TIP]
Expand Down Expand Up @@ -1342,6 +1378,8 @@ async def your_background_function(

### 5.11 Rate Limiting

> 📖 **[See rate limiting guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/rate-limiting/)**

To limit how many times a user can make a request in a certain interval of time (very useful to create subscription plans or just to protect your API against DDOS), you may just use the `rate_limiter_dependency` dependency:

```python
Expand Down Expand Up @@ -1456,6 +1494,8 @@ Note that for flexibility (since this is a boilerplate), it's not necessary to p

### 5.12 JWT Authentication

> 📖 **[See authentication guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/authentication/)**

#### 5.12.1 Details

The JWT in this boilerplate is created in the following way:
Expand Down Expand Up @@ -1641,6 +1681,8 @@ volumes:

## 6. Running in Production

> 📖 **[See production deployment guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/production/)**

### 6.1 Uvicorn Workers with Gunicorn

In production you may want to run using gunicorn to manage uvicorn workers:
Expand Down Expand Up @@ -1834,6 +1876,8 @@ And finally, on your browser: `http://localhost/docs`.

## 7. Testing

> 📖 **[See comprehensive testing guide in our docs](https://benavlabs.github.io/fastapi-boilerplate/user-guide/testing/)**

This project uses **fast unit tests** that don't require external services like databases or Redis. Tests are isolated using mocks and run in milliseconds.

### 7.1 Writing Tests
Expand Down
Binary file added docs/assets/FastAPI-boilerplate.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
163 changes: 163 additions & 0 deletions docs/getting-started/configuration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
# Configuration

This guide covers the essential configuration steps to get your FastAPI application running quickly.

## Quick Setup

The fastest way to get started is to copy the example environment file and modify just a few values:

```bash
cp src/.env.example src/.env
```

## Essential Configuration

Open `src/.env` and set these required values:

### Application Settings

```env
# App Settings
APP_NAME="Your app name here"
APP_DESCRIPTION="Your app description here"
APP_VERSION="0.1"
CONTACT_NAME="Your name"
CONTACT_EMAIL="Your email"
LICENSE_NAME="The license you picked"
```

### Database Connection

```env
# Database
POSTGRES_USER="your_postgres_user"
POSTGRES_PASSWORD="your_password"
POSTGRES_SERVER="localhost" # Use "db" for Docker Compose
POSTGRES_PORT=5432 # Use 5432 for Docker Compose
POSTGRES_DB="your_database_name"
```

### PGAdmin (Optional)

For database administration:

```env
# PGAdmin
PGADMIN_DEFAULT_EMAIL="your_email_address"
PGADMIN_DEFAULT_PASSWORD="your_password"
PGADMIN_LISTEN_PORT=80
```

**To connect to database in PGAdmin:**
1. Login with `PGADMIN_DEFAULT_EMAIL` and `PGADMIN_DEFAULT_PASSWORD`
2. Click "Add Server"
3. Use these connection settings:
- **Hostname/address**: `db` (if using containers) or `localhost`
- **Port**: Value from `POSTGRES_PORT`
- **Database**: `postgres` (leave as default)
- **Username**: Value from `POSTGRES_USER`
- **Password**: Value from `POSTGRES_PASSWORD`

### Security

Generate a secret key and set it:

```bash
# Generate a secure secret key
openssl rand -hex 32
```

```env
# Cryptography
SECRET_KEY="your-generated-secret-key-here" # Result of openssl rand -hex 32
ALGORITHM="HS256" # Default: HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30 # Default: 30
REFRESH_TOKEN_EXPIRE_DAYS=7 # Default: 7
```

### First Admin User

```env
# Admin User
ADMIN_NAME="your_name"
ADMIN_EMAIL="your_email"
ADMIN_USERNAME="your_username"
ADMIN_PASSWORD="your_password"
```

### Redis Configuration

```env
# Redis Cache
REDIS_CACHE_HOST="localhost" # Use "redis" for Docker Compose
REDIS_CACHE_PORT=6379

# Client-side Cache
CLIENT_CACHE_MAX_AGE=30 # Default: 30 seconds

# Redis Job Queue
REDIS_QUEUE_HOST="localhost" # Use "redis" for Docker Compose
REDIS_QUEUE_PORT=6379

# Redis Rate Limiting
REDIS_RATE_LIMIT_HOST="localhost" # Use "redis" for Docker Compose
REDIS_RATE_LIMIT_PORT=6379
```

!!! warning "Redis in Production"
You may use the same Redis instance for caching and queues while developing, but use separate containers in production.

### Rate Limiting Defaults

```env
# Default Rate Limits
DEFAULT_RATE_LIMIT_LIMIT=10 # Default: 10 requests
DEFAULT_RATE_LIMIT_PERIOD=3600 # Default: 3600 seconds (1 hour)
```

### First Tier

```env
# Default Tier
TIER_NAME="free"
```

## Environment Types

Set your environment type:

```env
ENVIRONMENT="local" # local, staging, or production
```

- **local**: API docs available at `/docs`, `/redoc`, and `/openapi.json`
- **staging**: API docs available to superusers only
- **production**: API docs completely disabled

## Docker Compose Settings

If using Docker Compose, use these values instead:

```env
# Docker Compose values
POSTGRES_SERVER="db"
REDIS_CACHE_HOST="redis"
REDIS_QUEUE_HOST="redis"
REDIS_RATE_LIMIT_HOST="redis"
```

## Optional Services

The boilerplate includes Redis for caching, job queues, and rate limiting. If running locally without Docker, either:

1. **Install Redis** and keep the default settings
2. **Disable Redis services** (see [User Guide - Configuration](../user-guide/configuration/index.md) for details)

## That's It!

With these basic settings configured, you can start the application:

- **Docker Compose**: `docker compose up`
- **Manual**: `uv run uvicorn src.app.main:app --reload`

For detailed configuration options, advanced settings, and production deployment, see the [User Guide - Configuration](../user-guide/configuration/index.md).
Loading