Skip to main content

A package to generate FastAPI project structures.

Project description

FastAPI Project Generator

PyPI version Python versions License

A pip package to generate FastAPI project structures with best practices. This tool helps you quickly bootstrap a new FastAPI application with a modular and scalable architecture.


Table of Contents


Features

  • Modular Structure: Follows best practices for scalable applications, separating concerns into different modules.
  • Includes schemas and utils: Provides directories for Pydantic schemas and utility functions.
  • Database Integration: Ready-to-use setup with SQLAlchemy and SQLite.
  • Authentication Placeholder: Includes a basic authentication dependency for future extension.
  • Testing Setup: Comes with a basic testing framework using pytest.
  • Environment Configuration: Uses python-dotenv for environment variable management.
  • Quick Start: Initialize a new project with a single command.

Installation

Requires Python 3.6 or higher.

Install the package using pip:

pip install fastapi-project-generator

Usage

Create a new FastAPI project by running:

fastapi-init my_new_project --description "My new FastAPI application"

This command will generate a new FastAPI project in the my_new_project directory with the specified description.

Command-Line Options

  • project_name: The name of your new project directory.
  • --description: (Optional) A short description of your project.

Project Structure

The generated project follows a modular structure:

my_new_project/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── core/
│   │   └── config.py
│   ├── models/
│   │   └── user.py
│   ├── schemas/
│   │   └── user.py
│   ├── routers/
│   │   └── users.py
│   ├── dependencies/
│   │   ├── __init__.py
│   │   ├── auth.py
│   │   └── get_db.py
│   ├── utils/
│   │   └── helpers.py
│   ├── db/
│   │   ├── base.py
│   │   └── session.py
│   └── tests/
│       └── test_main.py
├── .env
├── requirements.txt
└── README.md

Generated Files

app/main.py

The entry point of your application:

from fastapi import FastAPI
from app.routers import users

app = FastAPI(title="my_new_project")

app.include_router(users.router)

@app.get("/")
async def read_root():
    return {"message": "Welcome to my_new_project API"}

app/core/config.py

Handles configuration using environment variables:

import os
from dotenv import load_dotenv

load_dotenv()

class Settings:
    PROJECT_NAME: str = "my_new_project"
    DATABASE_URL: str = os.getenv("DATABASE_URL", "sqlite:///./test.db")

settings = Settings()

app/models/user.py

Defines the SQLAlchemy User model:

from sqlalchemy import Column, Integer, String
from app.db.base import Base

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True)
    email = Column(String, unique=True, index=True)
    hashed_password = Column(String)

app/schemas/user.py

Contains Pydantic models for data validation:

from pydantic import BaseModel

class UserBase(BaseModel):
    username: str
    email: str

class UserCreate(UserBase):
    password: str

class User(UserBase):
    id: int

    class Config:
        orm_mode = True

app/routers/users.py

API endpoints for user operations:

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import schemas, models
from app.dependencies.get_db import get_db

router = APIRouter(
    prefix="/users",
    tags=["users"],
    responses={404: {"description": "Not found"}},
)

@router.post("/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    db_user = models.User(
        username=user.username,
        email=user.email,
        hashed_password=user.password  # Note: Hash passwords in production!
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

@router.get("/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = db.query(models.User).filter(models.User.id == user_id).first()
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user

.env

Environment variables configuration:

PROJECT_NAME=my_new_project
DATABASE_URL=sqlite:///./test.db

Customization

You can customize the generated project according to your needs:

  • Change the Database: Update DATABASE_URL in .env and modify app/db/session.py accordingly.
  • Add New Models and Schemas: Create new files in app/models/ and app/schemas/.
  • Implement Authentication: Extend app/dependencies/auth.py with actual authentication logic.
  • Add More Routers: Create new router files in app/routers/ and include them in app/main.py.

Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository on GitHub.
  2. Create a new branch for your feature or bug fix.
  3. Commit your changes with clear messages.
  4. Push your branch to your forked repository.
  5. Create a pull request to the main repository.

License

This project is licensed under the MIT License.


Contact


Acknowledgments

  • FastAPI for providing an excellent framework.
  • Click and Jinja2 for CLI and templating support.
  • The Python community for their invaluable resources and contributions.

Additional Information

Running the Application

Navigate to your new project directory and install dependencies:

cd my_new_project
pip install -r requirements.txt

Run the application using Uvicorn:

uvicorn app.main:app --reload

Testing

Run tests using pytest:

pytest

Keywords

fastapi, generator, template, project, scaffolding, code generation, python, cli, development, starter kit


Project URLs


By using this tool, you agree to the terms of the MIT License.


Contributing Guidelines

  • Code Style: Follow PEP 8 guidelines.
  • Commits: Write clear and concise commit messages.
  • Pull Requests: Describe the changes and why they are necessary.
  • Issues: Use the issue tracker to report bugs or request features.

Support

If you encounter any problems or have questions, feel free to open an issue on GitHub or contact the author directly.


Thank you for using FastAPI Project Generator! Happy coding!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_project_generator-0.1.4.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_project_generator-0.1.4-py3-none-any.whl (14.6 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_project_generator-0.1.4.tar.gz.

File metadata

File hashes

Hashes for fastapi_project_generator-0.1.4.tar.gz
Algorithm Hash digest
SHA256 ccb87e6c819cf5098c4d83363e39eace21179dcf33efe3dff246c4701e82b5fc
MD5 2215193b73a027025508b1b85abdc2f9
BLAKE2b-256 933eda6b6d563a20a8b15499781f5684af2411a71e74e2a051835b5b26ed5ff8

See more details on using hashes here.

File details

Details for the file fastapi_project_generator-0.1.4-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_project_generator-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 8e5eac2e25f38fb5552984784ef15cd4ab2681cb97628a96d872e9ae2f86d9f8
MD5 c612fd50de39baaa0a936058beef328d
BLAKE2b-256 f9a22fe9b3237090efa2be5fc4a9184129fbcf94c0d6e9835a6286ef7ed63b14

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page