Skip to content

GhaziRiyadh/FastAPI-CRUD

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

FastAPI SQLModel CRUD Generator πŸš€

A powerful, production-ready FastAPI boilerplate with automatic CRUD API generation using SQLModel and async PostgreSQL.

FastAPI Python PostgreSQL SQLModel

✨ Features

  • ⚑ Automatic CRUD API Generation - Generate complete REST APIs with a single command
  • πŸ—„οΈ Async PostgreSQL Support - Built with SQLModel and asyncpg for high performance
  • πŸ—‘οΈ Soft Delete - Built-in soft delete with restore functionality
  • πŸ›‘οΈ Type Safety - Full Python type hints and Pydantic validation
  • πŸ—οΈ Clean Architecture - Proper separation of concerns with repository pattern
  • πŸ”§ CLI Tool - Scaffold new apps and models quickly
  • πŸ“š Auto Documentation - Automatic OpenAPI/Swagger documentation
  • πŸš€ Production Ready - Error handling, logging, and health checks

πŸš€ Quick Start

Prerequisites

  • Python 3.8+
  • PostgreSQL 12+

Installation

  1. Clone and install:
git clone <your-repo-url>
cd my-api
pip install poetry
poetry install --no-root
  1. Setup database:
createdb mydatabase
cp .env.example .env
# Edit .env with your database credentials
  1. Create your first API:
python cli.py full blog Post -f "title:str,content:str,author:str"
  1. Run the server:
poetry run fastapi dev src/main.py --host 0.0.0.0 

Visit http://localhost:8000/docs to see your auto-generated API documentation!

πŸ“– CLI Usage

Generate Complete Apps

# Create a blog app with Post model
python cli.py full blog Post -f "title:str,content:str,author:str"

# Add more models to existing app
python cli.py model blog Comment -f "content:str,post_id:int,author:str"
python cli.py model blog Category -f "name:str,description:str"

Step-by-Step Creation

# Create app structure first
python cli.py app_create blog

# Then add models
python cli.py model blog Post -f "title:str,content:str"

List Existing Apps

python cli.py list_apps

🎯 Generated API Endpoints

Each model automatically gets these REST endpoints:

Method Endpoint Description Example
GET /{models} List items (paginated) GET /api/v1/posts
GET /{models}/{id} Get item by ID GET /api/v1/posts/1
POST /{models} Create new item POST /api/v1/posts
PUT /{models}/{id} Update item PUT /api/v1/posts/1
DELETE /{models}/{id} Soft delete DELETE /api/v1/posts/1
PATCH /{models}/{id}/restore Restore item PATCH /api/v1/posts/1/restore
DELETE /{models}/{id}/force Permanent delete DELETE /api/v1/posts/1/force

πŸ’‘ Example Usage

Create a Post

curl -X POST "http://localhost:8000/api/v1/posts" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "My First Post",
    "content": "This is the content",
    "author": "John Doe"
  }'

List Posts with Pagination

curl "http://localhost:8000/api/v1/posts?page=1&per_page=10"

Update a Post

curl -X PUT "http://localhost:8000/api/v1/posts/1" \
  -H "Content-Type: application/json" \
  -d '{"title": "Updated Title"}'

πŸ—οΈ Project Structure

src/
β”œβ”€β”€ core/                    # Framework core
β”‚   β”œβ”€β”€ bases/              # Base classes (Repository, Service, Router)
β”‚   β”œβ”€β”€ database.py         # DB configuration & models
β”‚   β”œβ”€β”€ exceptions.py       # Custom exceptions
β”‚   └── cli.py             # Code generator CLI
└── apps/                   # Your business apps
    └── blog/
        β”œβ”€β”€ models/         # SQLModel classes
        β”œβ”€β”€ repositories/   # Data access layer
        β”œβ”€β”€ services/       # Business logic
        β”œβ”€β”€ routers/        # API routes
        └── schemas/        # Pydantic schemas

βš™οΈ Configuration

Environment Variables (.env)

DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/mydatabase
SECRET_KEY=your-super-secret-key
ENVIRONMENT=development
DEBUG=True

Custom Model Example

from src.core.database import BaseModel
from sqlmodel import Field

class Post(BaseModel, table=True):
    __tablename__ = "blog_posts"
    
    title: str = Field()
    content: str = Field()
    author: str = Field()

Custom Business Logic

class PostService(BaseService[Post]):
    async def _validate_create(self, create_data: Dict[str, Any]) -> None:
        if len(create_data.get('title', '')) < 5:
            raise ValidationException("Title must be at least 5 characters")

πŸ› οΈ Development

Running the Server

# Development with auto-reload
python main.py

# Or using uvicorn
uvicorn main:app --reload --host 0.0.0.0 --port 8000

Access Points

πŸš€ Deployment

Production Setup

# Update environment
ENVIRONMENT=production
DEBUG=False

# Run with production settings
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

Docker Example

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

πŸ”§ Troubleshooting

Common Issues

Table doesn't exist error:

  • Ensure models are imported in database.py
  • Restart server after creating new models

Database connection issues:

  • Verify PostgreSQL is running
  • Check DATABASE_URL in .env file

Import errors:

  • Check Python path and module structure
  • Verify all __init__.py files exist

🀝 Contributing

We welcome contributions! Please feel free to submit pull requests or open issues for bugs and feature requests.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments


⭐ Star this repo if you find it helpful!


Built with ❀️ using FastAPI and SQLModel

About

A powerful CLI tool and boilerplate for automatically generating production-ready REST APIs using FastAPI, SQLModel, and async PostgreSQL.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors