Skip to content

Releases: benavlabs/FastAPI-boilerplate

0.14.0

02 Jul 04:53
01632e2
Compare
Choose a tag to compare

Benav Labs FastAPI boilerplate

Yet another template to speed your FastAPI development up, now with proper docs and an admin panel.

Python FastAPI Pydantic PostgreSQL Redis Docker NGINX


What's Changed

New Contributors

Full Changelog: v0.13.0...v0.14.0

📖 Documentation

📚 Visit our comprehensive documentation at benavlabs.github.io/FastAPI-boilerplate

⚠️ Documentation Status

This is our first version of the documentation. While functional, we acknowledge it's rough around the edges - there's a huge amount to document and we needed to start somewhere! We built this foundation (with a lot of AI assistance) so we can improve upon it.

Better documentation, examples, and guides are actively being developed. Contributions and feedback are greatly appreciated!

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:

  • FastAPI: modern Python web framework for building APIs
  • Pydantic V2: the most widely used data Python validation library, rewritten in Rust (5x-50x faster)
  • SQLAlchemy 2.0: Python SQL toolkit and Object Relational Mapper
  • PostgreSQL: The World's Most Advanced Open Source Relational Database
  • Redis: Open source, in-memory data store used by millions as a cache, message broker and more.
  • ARQ Job queues and RPC in python with asyncio and redis.
  • Docker Compose With a single command, create and start all the services from your configuration.
  • NGINX High-performance low resource consumption web server used for Reverse Proxy and Load Balancing.

Tip

There's a SQLModel version as well, but it's no longer updated: SQLModel-boilerplate.

1. Features

  • ⚡️ Fully async
  • 🚀 Pydantic V2 and SQLAlchemy 2.0
  • 🔐 User authentication with JWT
  • 🍪 Cookie based refresh token
  • 🏬 Easy redis caching
  • 👜 Easy client-side caching
  • 🚦 ARQ integration for task queue
  • ⚙️ Efficient and robust queries with fastcrud
  • ⎘ Out of the box offset and cursor pagination support with fastcrud
  • 🛑 Rate Limiter dependency
  • 👮 FastAPI docs behind authentication and hidden based on the environment
  • 🔧 Modern and light admin interface powered by CRUDAdmin
  • 🚚 Easy running with docker compose
  • ⚖️ NGINX Reverse Proxy and Load Balancing

2. Contents

  1. About
  2. Features
  3. Contents
  4. Prerequisites
    1. Environment Variables (.env)
    2. Docker Compose
    3. From Scratch
  5. Usage
    1. Docker Compose
    2. From Scratch
      1. Packages
      2. Running PostgreSQL With Docker
      3. Running Redis with Docker
      4. Running the API
    3. Creating the first superuser
    4. Database Migrations
  6. Extending
    1. Project Structure
    2. Database Model
    3. SQLAlchemy Models
    4. Pydantic Schemas
    5. Alembic Migrations
    6. CRUD
    7. Routes
      1. Paginated Responses
      2. HTTP Exceptions
    8. Caching
    9. More Advanced Caching
    10. ARQ Job Queues
    11. Rate Limiting
    12. JWT Authentication
    13. Admin Panel
    14. Running
    15. Create Application
    16. Opting Out of Services
  7. Running in Production
    1. Uvicorn Workers with Gunicorn
    2. Running With NGINX
      1. One Server
      2. Multiple Servers
  8. Testing
  9. Contributing
  10. References
  11. [Licens...
Read more

0.13.0

09 May 02:54
4c1f9af
Compare
Choose a tag to compare

0.13.0 Summary

 🚀Features

 🔎Bug fixes

  • minor mypy and ruff fixes
  • gunicorn bumped, security issue fixed
  • fastcrud bumped to 0.12.0 with bug fixes

What's Changed

Full Changelog: v0.12.4...v0.13.0

0.12.4

22 Feb 08:51
45781d7
Compare
Choose a tag to compare

0.12.4 Summary

 🚀Features

  • improved scripts logging

 🔎Bug fixes

  • remove db.commit() from async_get_db - thanks @mithun2003
  • using fastcrud, result from get is no longer a db_row object, so no longer passing it in delete

What's Changed

  • logging added to scripts, get_db fix, endpoints fixed for fastcrud usage by @igorbenav in #121

Full Changelog: v0.12.3...v0.12.4

0.12.3

15 Feb 03:28
b1a8370
Compare
Choose a tag to compare

0.12.3

 🔎Bug fixes

What's Changed

New Contributors

Full Changelog: v0.12.2...v0.12.3

0.12.2

11 Feb 21:59
189d5fd
Compare
Choose a tag to compare

0.12.2

⚡️Enhancements

  • now using recommended lifespan events instead of startup and shutdown events
  • libs bumped

 🔎Bug fixes

  • wrong .env reference in docker-compose fixed

What's Changed

Full Changelog: v0.11.1...v0.12.2

0.11.1

03 Feb 19:17
444ce98
Compare
Choose a tag to compare

0.11.1

 🔎Bug fixes

Warning

Content-Type Header ReDoS - FastAPI vulnerability fixed

Update python-multipart to 0.0.7 as soon as possible.

https://github.com/tiangolo/fastapi/security/advisories/GHSA-qf9m-vfgh-m389

What's Changed

Full Changelog: v0.11.0...v0.11.1

0.11.0

24 Jan 06:19
2694534
Compare
Choose a tag to compare

0.11.0 Summary

 🚀Features

  • replaced CRUDBase with fastcrud for more robust operations
  • worker script refactored, thanks @AlessioBugetti
  • print statements removed, thanks @shreyasSarve
  • PGAdmin container for PostgreSQL administration and debugging, thanks @gmirsky
  • create_tables_on_start parameter added in setup function
  • ruff added as pre-commit, thanks @luca-medeiros

📝Docs

  • all docs updated to reflect changes
  • pull request template added
  • Contributing moved to its own file and enhanced
  • Issue template added
  • Code of conduct added

1. fastcrud

Set Up FastAPI and FastCRUD

from fastapi import FastAPI
from fastcrud import FastCRUD, crud_router
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

# Database setup (Async SQLAlchemy)
DATABASE_URL = "sqlite+aiosqlite:///./test.db"
engine = create_async_engine(DATABASE_URL, echo=True)
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

# FastAPI app
app = FastAPI()

# CRUD operations setup
crud = FastCRUD(Item)

# CRUD router setup
item_router = crud_router(
    session=async_session,
    model=Item,
    crud=crud,
    create_schema=ItemCreateSchema,
    update_schema=ItemUpdateSchema,
    path="/items",
    tags=["Items"]
)

app.include_router(item_router)

Using FastCRUD in User-Defined FastAPI Endpoints

For more control over your endpoints, you can use FastCRUD directly within your custom FastAPI route functions. Here's an example:

Usage:

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from fastcrud import FastCRUD

from yourapp.models import Item
from yourapp.schemas import ItemCreateSchema, ItemUpdateSchema

app = FastAPI()

# Assume async_session is already set up as per the previous example

# Instantiate FastCRUD with your model
item_crud = FastCRUD(Item)

@app.post("/custom/items/")
async def create_item(item_data: ItemCreateSchema, db: AsyncSession = Depends(async_session)):
    return await item_crud.create(db, item_data)

@app.get("/custom/items/{item_id}")
async def read_item(item_id: int, db: AsyncSession = Depends(async_session)):
    item = await item_crud.get(db, id=item_id)
    if not item:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

# You can add more routes for update and delete operations in a similar fashion

To know all available methods, check it in fastcrud readme.

2. create_tables_on_start

If you want to stop tables from being created every time you run the api, you should disable this here:

# app/main.py

from .api import router
from .core.config import settings
from .core.setup import create_application

# create_tables_on_start defaults to True
app = create_application(router=router, settings=settings, create_tables_on_start=False)

 🔎Bug fixes

  • pyproject.toml fixed, thanks @DmitryIo
  • get task endpoint bug fixed
  • deprecated typing classes replaced, thanks @eredden

What's Changed

New Contributors

Full Changelog: v0.10.0...v0.11.0

0.10.0

28 Dec 03:32
ecf206d
Compare
Choose a tag to compare

0.10.0 Summary

 🚀Features

  • datetime refactored to be timezone aware #79 #82 (thanks @mithun2003)
  • passlib replaced with bcryptfor password hashing #74
  • pydantic validator moved to v2 field_Validator #72
  • config port data type consistency #69 (thanks @luca-medeiros)
  • pyproject.toml moved to the root folder #65
  • Tests folder moved to core, imports changed to relative imports #65

📝Docs

  • Now there's the option to use a template for .env, docker-compose.yml and Dockerfile:

Tip

If you are in a hurry, you may use one of the following templates (containing a .env, docker-compose.yml and Dockerfile):

Warning

Do not forget to place docker-compose.yml and Dockerfile in the root folder, while .env should be in the src folder.

  • Docs to run with NGINX were revised and are clearer now

🔎Bug fixes

  • CRUDBase count method fixed when kwargs is none #81
  • pydantic allow_reuse removed #70
  • pagination bug fixed #66
  • mypy multiple type hint fixes

What's Changed

New Contributors🎉

Full Changelog: v0.9.0...v0.10.0

0.9.0

30 Nov 03:38
5b6229f
Compare
Choose a tag to compare

0.9.0 Summary

 🚀Features

  • JWT Authentication now supports refresh token🎉

📝Docs

🔐JWT Authentication With Refresh Token

The JWT in the boilerplate was updated to work in the following way:

  1. JWT Access Tokens: how you actually access protected resources is passing this token in the request header.
  2. Refresh Tokens: you use this type of token to get an access token, which you'll use to access protected resources.

The access token is short lived (default 30 minutes) to reduce the damage of a potential leak. The refresh token, on the other hand, is long lived (default 7 days), and you use it to renew your access token without the need to provide username and password every time it expires.

Since the refresh token lasts for a longer time, it's stored as a cookie in a secure way:

# app/api/v1/login

...
response.set_cookie(
    key="refresh_token",
    value=refresh_token,
    httponly=True,               # Prevent access through JavaScript
    secure=True,                 # Ensure cookie is sent over HTTPS only
    samesite='Lax',              # Default to Lax for reasonable balance between security and usability
    max_age=<number_of_seconds>  # Set a max age for the cookie
)
...

You may change it to suit your needs. The possible options for samesite are:

  • Lax: Cookies will be sent in top-level navigations (like clicking on a link to go to another site), but not in API requests or images loaded from other sites.
  • Strict: Cookies will be sent in top-level navigations (like clicking on a link to go to another site), but not in API requests or images loaded from other sites.
  • None: Cookies will be sent with both same-site and cross-site requests.

🚀Usage

What you should do with the client is:

  • Login: Send credentials to /api/v1/login. Store the returned access token in memory for subsequent requests.
  • Accessing Protected Routes: Include the access token in the Authorization header.
  • Token Renewal: On access token expiry, the front end should automatically call /api/v1/refresh for a new token.
  • Login Again: If refresh token is expired, credentials should be sent to /api/v1/login again, storing the new access token in memory.
  • Logout: Call /api/v1/logout to end the session securely.

This authentication setup in the provides a robust, secure, and user-friendly way to handle user sessions in your API applications.

What's Changed

Full Changelog: v0.8.3...v0.9.0

0.8.3

29 Nov 00:12
6c6ed34
Compare
Choose a tag to compare

0.8.3 Summary

  • Docker Compose improved
  • docs for running with docker compose improved

🔎Bug fixes

  • Expose used now in docker compose
  • Docs fixed to use the boilerplate with docker compose

What's Changed

  • Some corrections and improvements to run with docker compose by @YuriiMotov in #62

New Contributors

Full Changelog: v0.8.2...v0.8.3