fastapi-project-generator 0.1.4
A package to generate FastAPI project structures.
Requires Python: >=3.6

# FastAPI Project Generator

[![PyPI version](https://img.shields.io/pypi/v/fastapi-project-generator.svg)](https://pypi.org/project/fastapi-project-generator/)
[![Python versions](https://img.shields.io/pypi/pyversions/fastapi-project-generator.svg)](https://pypi.org/project/fastapi-project-generator/)
[![License](https://img.shields.io/pypi/l/fastapi-project-generator.svg)](https://github.com/yourusername/fastapi-project-generator/blob/main/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](#features)
- [Installation](#installation)
- [Usage](#usage)
- [Project Structure](#project-structure)
- [Generated Files](#generated-files)
- [Customization](#customization)
- [Contributing](#contributing)
- [License](#license)
- [Contact](#contact)

---

## 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`:

```bash
pip install fastapi-project-generator
```

---

## Usage

Create a new FastAPI project by running:

```bash
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:

```python
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:

```python
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:

```python
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:

```python
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:

```python
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:

```env
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](https://github.com/Synacal/fastapi-project-template).
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](https://github.com/Synacal/fastapi-project-template/blob/main/LICENSE).

---

## Contact

- **Author**: Nirodya Pussadeniya
- **Email**: [nirodya@synacal.ai](mailto:nirodya@synacal.ai)
- **GitHub**: [Pusse-01](https://github.com/Pusse-01)
- **Project Link**: [GitHub Repository](https://github.com/Synacal/fastapi-project-template)

---

## Acknowledgments

- [FastAPI](https://fastapi.tiangolo.com/) for providing an excellent framework.
- [Click](https://click.palletsprojects.com/) and [Jinja2](https://jinja.palletsprojects.com/) 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:

```bash
cd my_new_project
pip install -r requirements.txt
```

Run the application using Uvicorn:

```bash
uvicorn app.main:app --reload
```

### Testing

Run tests using `pytest`:

```bash
pytest
```

---

# Keywords

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

---

# Project URLs

- **Documentation**: [GitHub README](https://github.com/Synacal/fastapi-project-template#readme)
- **Source**: [GitHub Repository](https://github.com/Synacal/fastapi-project-template)
- **Issue Tracker**: [GitHub Issues](https://github.com/Synacal/fastapi-project-template/issues)

---

By using this tool, you agree to the terms of the [MIT License](https://github.com/Synacal/fastapi-project-template/blob/main/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!