Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
7bf6194
ci: add lint and test workflow
LacerdaTraderCode Oct 9, 2026
5579210
build: add ruff configuration
LacerdaTraderCode Oct 9, 2026
0f7a206
test: add pytest configuration
LacerdaTraderCode Oct 9, 2026
22bc1fb
build: add development requirements
LacerdaTraderCode Oct 9, 2026
038b9dd
build: add missing email-validator and pin bcrypt
LacerdaTraderCode Oct 9, 2026
a09e0c0
refactor: translate main module to English
LacerdaTraderCode Oct 9, 2026
20323b6
refactor: translate auth module to English
LacerdaTraderCode Oct 9, 2026
5dc5206
refactor: translate database module to English
LacerdaTraderCode Oct 9, 2026
0cce8d0
refactor: translate models module to English
LacerdaTraderCode Oct 9, 2026
44b2563
refactor: translate schemas module to English
LacerdaTraderCode Oct 9, 2026
c607c4e
refactor: translate auth router to English
LacerdaTraderCode Oct 9, 2026
03e3551
refactor: translate items router and extract ownership lookup
LacerdaTraderCode Oct 9, 2026
2c596cd
refactor: translate users router to English
LacerdaTraderCode Oct 9, 2026
a874ebb
test: add tests package
LacerdaTraderCode Oct 9, 2026
a1ddd1a
test: add shared fixtures with isolated in-memory database
LacerdaTraderCode Oct 9, 2026
79cbe0f
test: cover password hashing, tokens, registration and login
LacerdaTraderCode Oct 9, 2026
e2dabf4
test: cover items CRUD, pagination and ownership isolation
LacerdaTraderCode Oct 9, 2026
bac81e6
test: cover health, root and current user endpoints
LacerdaTraderCode Oct 9, 2026
9c7492a
docs: add environment variables example
LacerdaTraderCode Oct 9, 2026
5a804f1
docs: add CI badge, test instructions and accurate structure
LacerdaTraderCode Oct 9, 2026
b40e612
docs: document project structure and testing
LacerdaTraderCode Oct 9, 2026
f88fce4
docs: add development section
LacerdaTraderCode Oct 9, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
SECRET_KEY=change-this-key-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
DATABASE_URL=sqlite:///./app.db
23 changes: 23 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: CI

on:
push:
branches: [main]
pull_request:
branches: [main]

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- name: Install dependencies
run: pip install -r requirements-dev.txt
- name: Lint
run: ruff check . && ruff format --check .
- name: Run tests
run: pytest -v
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

**A professional REST API template with JWT, full CRUD, and Swagger**

[![CI](https://github.com/LacerdaTraderCode/fastapi-rest-boilerplate/actions/workflows/ci.yml/badge.svg)](https://github.com/LacerdaTraderCode/fastapi-rest-boilerplate/actions/workflows/ci.yml)
[![Python](https://img.shields.io/badge/Python-3.11%2B-blue?logo=python&logoColor=white)](https://www.python.org/)
[![FastAPI](https://img.shields.io/badge/FastAPI-005571?logo=fastapi)](https://fastapi.tiangolo.com/)
[![SQLAlchemy](https://img.shields.io/badge/SQLAlchemy-D71F00?logo=sqlalchemy&logoColor=white)](https://www.sqlalchemy.org/)
Expand Down Expand Up @@ -53,9 +54,13 @@ fastapi-rest-boilerplate/
│ ├── schemas.py # Pydantic schemas
│ ├── auth.py # JWT logic
│ └── routers/
│ ├── auth.py # Registration and login
│ ├── users.py # User endpoints
│ └── items.py # Item endpoints (CRUD)
├── tests/
├── .github/workflows/ci.yml
├── requirements.txt
├── requirements-dev.txt
├── .env.example
└── README.md
```
Expand Down Expand Up @@ -128,6 +133,18 @@ curl -X GET "http://localhost:8000/items/" \

---

## 🧪 Development

```bash
pip install -r requirements-dev.txt
ruff check . && ruff format --check .
pytest -v
```

Tests run against an isolated in-memory SQLite database. The same checks run on every push and pull request via GitHub Actions.

---

## 🚀 Deploy

Ready for deployment on:
Expand Down
36 changes: 11 additions & 25 deletions app/auth.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,38 @@
"""
Módulo de autenticação - gerencia hash de senhas e tokens JWT.
"""
import os
from datetime import datetime, timedelta, timezone
from typing import Optional
from datetime import UTC, datetime, timedelta

from jose import JWTError, jwt
from passlib.context import CryptContext
from dotenv import load_dotenv
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
from sqlalchemy.orm import Session
from dotenv import load_dotenv

from app.database import get_db
from app.models import User
from app.schemas import TokenData

load_dotenv()

# Configurações de segurança (em produção, use variáveis de ambiente)
SECRET_KEY = os.getenv("SECRET_KEY", "mude_esta_chave_em_producao")
SECRET_KEY = os.getenv("SECRET_KEY", "change-this-key-in-production")
ALGORITHM = os.getenv("ALGORITHM", "HS256")
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "30"))

# Context para hash de senhas
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# OAuth2 scheme
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")


def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verifica se a senha em texto plano bate com o hash."""
return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password: str) -> str:
"""Gera hash bcrypt da senha."""
return pwd_context.hash(password)


def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
"""Cria token JWT com os dados fornecidos e expiração."""
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
to_encode = data.copy()
expire = datetime.now(timezone.utc) + (
expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
)
expire = datetime.now(UTC) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

Expand All @@ -54,21 +41,20 @@ def get_current_user(
token: str = Depends(oauth2_scheme),
db: Session = Depends(get_db),
) -> User:
"""Extrai e valida o usuário a partir do token JWT."""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Credenciais inválidas",
detail="Invalid credentials",
headers={"WWW-Authenticate": "Bearer"},
)

try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email: str = payload.get("sub")
email: str | None = payload.get("sub")
if email is None:
raise credentials_exception
token_data = TokenData(email=email)
except JWTError:
raise credentials_exception
except JWTError as exc:
raise credentials_exception from exc

user = db.query(User).filter(User.email == token_data.email).first()
if user is None:
Expand Down
12 changes: 3 additions & 9 deletions app/database.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
"""
Configuração da conexão com o banco de dados via SQLAlchemy.
"""
import os
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

load_dotenv()

# URL do banco (padrão: SQLite local)
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./app.db")

# Para SQLite precisamos do connect_args, para outros bancos não
connect_args = {"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {}

engine = create_engine(DATABASE_URL, connect_args=connect_args)
Expand All @@ -21,7 +16,6 @@


def get_db():
"""Dependency para obter sessão do banco nas rotas."""
db = SessionLocal()
try:
yield db
Expand Down
25 changes: 7 additions & 18 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,21 @@
"""
FastAPI REST Boilerplate - Ponto de entrada da aplicação.

Este módulo configura a aplicação FastAPI, CORS, e registra as rotas.
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.database import engine, Base
from app.routers import users, items, auth
from app.database import Base, engine
from app.routers import auth, items, users

# Criar tabelas no banco de dados
Base.metadata.create_all(bind=engine)

# Inicializar aplicação
app = FastAPI(
title="FastAPI REST Boilerplate",
description="Template profissional de API REST com autenticação JWT",
description="REST API template with JWT authentication and CRUD",
version="1.0.0",
contact={
"name": "Wagner Lacerda",
"url": "https://github.com/LacerdaTraderCode",
},
)

# Configurar CORS (ajuste allow_origins em produção)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
Expand All @@ -32,23 +24,20 @@
allow_headers=["*"],
)

# Registrar rotas
app.include_router(auth.router, prefix="/auth", tags=["Autenticação"])
app.include_router(users.router, prefix="/users", tags=["Usuários"])
app.include_router(items.router, prefix="/items", tags=["Itens"])
app.include_router(auth.router, prefix="/auth", tags=["Auth"])
app.include_router(users.router, prefix="/users", tags=["Users"])
app.include_router(items.router, prefix="/items", tags=["Items"])


@app.get("/", tags=["Root"])
def read_root():
"""Endpoint raiz - health check."""
return {
"message": "FastAPI REST Boilerplate está rodando!",
"message": "FastAPI REST Boilerplate is running",
"docs": "/docs",
"version": "1.0.0",
}


@app.get("/health", tags=["Root"])
def health_check():
"""Endpoint de health check para monitoramento."""
return {"status": "healthy"}
9 changes: 1 addition & 8 deletions app/models.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
"""
Modelos SQLAlchemy - Representação das tabelas do banco de dados.
"""
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func

from app.database import Base


class User(Base):
"""Modelo de usuário do sistema."""
__tablename__ = "users"

id = Column(Integer, primary_key=True, index=True)
Expand All @@ -18,12 +14,10 @@ class User(Base):
is_active = Column(Boolean, default=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())

# Relacionamento com itens
items = relationship("Item", back_populates="owner", cascade="all, delete-orphan")


class Item(Base):
"""Modelo de item - exemplo de recurso CRUD."""
__tablename__ = "items"

id = Column(Integer, primary_key=True, index=True)
Expand All @@ -33,5 +27,4 @@ class Item(Base):
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())

# Relacionamento com usuário
owner = relationship("User", back_populates="items")
30 changes: 4 additions & 26 deletions app/routers/auth.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,24 @@
"""
Router de autenticação - endpoints de registro e login.
"""
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from app.auth import create_access_token, get_password_hash, verify_password
from app.database import get_db
from app.models import User
from app.schemas import UserCreate, UserResponse, Token
from app.auth import (
get_password_hash,
verify_password,
create_access_token,
)
from app.schemas import Token, UserCreate, UserResponse

router = APIRouter()


@router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
def register(user: UserCreate, db: Session = Depends(get_db)):
"""
Registra um novo usuário no sistema.

- **email**: e-mail único do usuário
- **password**: senha (será armazenada com hash bcrypt)
"""
# Verificar se usuário já existe
existing_user = db.query(User).filter(User.email == user.email).first()
if existing_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="E-mail já cadastrado",
detail="Email already registered",
)

# Criar novo usuário com senha hasheada
new_user = User(
email=user.email,
hashed_password=get_password_hash(user.password),
Expand All @@ -49,18 +34,11 @@ def login(
form_data: OAuth2PasswordRequestForm = Depends(),
db: Session = Depends(get_db),
):
"""
Autentica usuário e retorna token JWT.

Envie form-data com os campos:
- **username**: e-mail do usuário
- **password**: senha
"""
user = db.query(User).filter(User.email == form_data.username).first()
if not user or not verify_password(form_data.password, user.hashed_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="E-mail ou senha incorretos",
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)

Expand Down
Loading
Loading