All-purpose template for your FastAPI projects

Posted by


Creating a universal template for your FastAPI projects can save you a lot of time and effort in the long run. By setting up a consistent structure and implementing common features from the start, you can streamline your development process and ensure that your projects are organized and maintainable.

In this tutorial, we will walk through the steps to create a universal template for your FastAPI projects. This template will include common features such as database configuration, authentication, error handling, and more. By following this tutorial, you can set up a solid foundation for all of your FastAPI projects moving forward.

Step 1: Setting Up Your Project Structure
To start, create a new directory for your project and navigate to it in your terminal. Inside this directory, create the following structure:

project/
├── app/
│   ├── api/
│   │   ├── __init__.py
│   │   └── routes/
│   │       └── __init__.py
│   ├── core/
│   │   ├── __init__.py
│   │   ├── config.py
│   │   ├── database.py
│   │   ├── models.py
│   │   └── security.py
│   ├── main.py
│   └── schemas/
│       ├── __init__.py
│       └── user.py
├── requirements.txt
└── main.py

Step 2: Setting Up Your Database
In the core directory, create a database.py file to set up your database connection using SQLAlchemy. Here is an example code snippet:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

Make sure to update the SQLALCHEMY_DATABASE_URL variable with your own database connection string.

Step 3: Setting Up User Authentication
In the core directory, create a security.py file to handle user authentication. Here is an example code snippet:

from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password):
    return pwd_context.hash(password)

Step 4: Setting Up Your Configurations
In the core directory, create a config.py file to store your application configurations. Here is an example code snippet:

from pydantic import BaseSettings

class Settings(BaseSettings):
    SECRET_KEY: str
    ALGORITHM: str
    ACCESS_TOKEN_EXPIRE_MINUTES: int

    class Config:
        env_file = ".env"

settings = Settings()

Create a .env file in your project root directory and add your application configurations like this:

SECRET_KEY="your_secret_key"
ALGORITHM="HS256"
ACCESS_TOKEN_EXPIRE_MINUTES=30

Step 5: Setting Up Your Models and Schemas
In the core directory, create a models.py file to define your database models using SQLAlchemy. Here is an example code snippet:

from sqlalchemy import Column, Integer, String
from core.database import Base

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True)
    password = Column(String)

class UserInDB(User):
    pass

In the schemas directory, create a user.py file to define Pydantic models for your API inputs and outputs. Here is an example code snippet:

from pydantic import BaseModel

class UserBase(BaseModel):
    username: str

class UserCreate(UserBase):
    password: str

class User(UserBase):
    id: int

    class Config:
        orm_mode = True

Step 6: Setting Up Your Routes
In the api directory, create a routes directory and an __init__.py file inside it to define your API routes. Here is an example code snippet:

from fastapi import APIRouter

router = APIRouter()

In the api directory, create an __init__.py file to include your API routes. Here is an example code snippet:

from fastapi import FastAPI
from app.api.routes import router

app = FastAPI()

app.include_router(router, prefix="/users", tags=["users"])

Step 7: Putting It All Together
In your main.py file, import your application and run it using uvicorn. Here is an example code snippet to put it all together:

from fastapi import FastAPI
from core.config import settings
from core.database import engine
from app.api import app

app = FastAPI()

@app.on_event("startup")
async def startup_event():
    engine

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)

Step 8: Running Your Application
To run your application, make sure you have all the required dependencies installed by running:

pip install -r requirements.txt

Then, run your application with:

python main.py

Your FastAPI project is now set up with a universal template that includes common features such as database configuration, authentication, error handling, and more. You can use this template as a starting point for all of your FastAPI projects, saving you time and effort in the long run. Happy coding!

0 0 votes
Article Rating

Leave a Reply

12 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@_samuro_
2 hours ago

Тебе уже говорили, что ты похож на Элвиса Пресли? 😀

@iJaVolo
2 hours ago

А на гитхабе этот репозиторий можно посмотреть? А дайте ссылку, пожалуйста

@sergeych8929
2 hours ago

Супер! Желательно проект с использованием web-шаблона (dashboard простенький с CRUD). Кстати, интересно предпочтение автора, что больше нравиться jinja2 или что-то другое?

@knowledgedose1956
2 hours ago

пробовал Tortoise ORM года два назад, в целом похоже на джанговскую, по крайней мере изначально, глубоко мы не зарывались с командой. естественно взяли известную админку, которую разрабатывает один человек, и наткнулись на кучу багов в админке. пришлось костылять на ходу. после этого отношусь скептично к ней. хотелось бы послушать от автора, сталкивался ли он с чем-то подобным, как обходил и тд. и в целом, стоит ли оно того.

@knowledgedose1956
2 hours ago

странная вырезка на 11:49 😮

@servera-center
2 hours ago

Что у тебя за терминал?

@erkanat_iman
2 hours ago

про Tortoise ORM жду

@nikulin7944
2 hours ago

Спасибо! Нужно продолжение!

@РусланА-ф2н
2 hours ago

Спасибо! Было очень полезно

@oleggov3395
2 hours ago

Очень интересно будет узнать о CRUD операциях с Tortoise ORM

@whosane9923
2 hours ago

Хотелось бы проект простенький , для лучшего понимания и как раз микро чек книгу закрепить ) двух зайцев с двухстволки )

@FedorRasputin-v6i
2 hours ago

Нужен курс по Tortoise ORM )

12
0
Would love your thoughts, please comment.x
()
x