Skip to content

Latest commit

 

History

History
292 lines (220 loc) · 6.83 KB

File metadata and controls

292 lines (220 loc) · 6.83 KB

Basic Flask REST API

A professional REST API built with Flask, following best practices of modular architecture, clean architecture, and design patterns. This project serves as a template for building scalable and maintainable APIs.

🚀 Features

  • Modular architecture (Blueprints) for maximum scalability
  • Layered separation: Controller, Service, Repository, Model
  • Data validation with Marshmallow
  • Database migrations with Flask-Migrate
  • Environment variables with python-dotenv
  • Correct HTTP verbs implementation (GET, POST, PUT, PATCH, DELETE)
  • Global error handling
  • Production-ready structure

📋 Prerequisites

  • Python 3.10+
  • pip (Python package manager)
  • virtualenv (recommended)
  • Git

🛠️ Technologies Used

  • Flask - Web framework
  • Flask-SQLAlchemy - Database ORM
  • Flask-Migrate - Database migrations
  • Flask-Marshmallow - Serialization and validation
  • python-dotenv - Environment variables
  • SQLite (development) / PostgreSQL (production)

📁 Project Structure

my_api_flask/
├── .env                          # Environment variables
├── config.py                     # Centralized configuration
├── run.py                        # Entry point
├── requirements.txt              # Dependencies
├── .gitignore
└── src/
     ├── __init__.py              # Application factory
     ├── extensions.py            # Flask extensions
     ├── utils/                   # Flask extensions
     └── modules/                 # Feature-based modules
         └── users/               # Users module
             ├── __init__.py
             ├── controller.py    # Routes (Blueprints)
             ├── service.py       # Business logic
             ├── model.py         # Data model
             ├── schema.py        # Marshmallow validation
             └── repository.py    # Data access layer

🔧 Installation

1. Clone the repository

# ssh
git clone git@github.com:alexdevzz/flask-basic-rest-api.git

# or https
git clone https://github.com/alexdevzz/flask-basic-rest-api.git

cd your-repository

2. Create virtual environment

# On macOS/Linux
python -m venv .venv
source venv/bin/activate

# On Windows
python -m venv .venv
venv\Scripts\activate

3. Install dependencies

pip install -r requirements.txt

4. Configure environment variables

Create a .env file in the project root:

# Flask configuration
FLASK_APP=run.py
FLASK_ENV=development
FLASK_DEBUG=1
SECRET_KEY=your-super-secret-key-change-in-production

# Database configuration
DATABASE_URL=sqlite:///app.db
# For PostgreSQL:
# DATABASE_URL=postgresql://username:password@localhost/my_db

# API configuration
API_TITLE="Rest API Example"
API_VERSION=v1

5. Initialize the database

# Initialize migrations (first time only)
flask db init

# Create the first migration
flask db migrate -m "Initial migration: create users table"

# Apply the migration
flask db upgrade

🚀 Run the application

# Method 1: Using flask run
flask run

# Method 2: Running run.py
python run.py

The API will be available at http://localhost:5000

📚 API Documentation

Available Endpoints

Method Endpoint Description
GET /api/v1/health API health check
GET /api/v1/users/ Get all users
GET /api/v1/users/{id} Get user by ID
POST /api/v1/users/ Create a new user
PUT /api/v1/users/{id} Completely replace a user
PATCH /api/v1/users/{id} Partially update a user
DELETE /api/v1/users/{id} Delete a user (soft delete)

Usage Examples

Health Check

curl http://localhost:5000/api/v1/health

Create User (POST)

curl -X POST http://localhost:5000/api/v1/users/ \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@email.com",
    "age": 30
  }'

Complete Update (PUT)

curl -X PUT http://localhost:5000/api/v1/users/1 \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Carlos Doe",
    "email": "johncarlos@email.com",
    "age": 31
  }'

Partial Update (PATCH)

curl -X PATCH http://localhost:5000/api/v1/users/1 \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Carlos"
  }'

🏗️ Project Architecture

Design Pattern: Layered Architecture

Client (HTTP Request)
    ↓
[Controller] - Handles HTTP requests, initial validation
    ↓
[Service] - Business logic, application rules
    ↓
[Repository] - Data access, database queries
    ↓
[Model] - Data representation (SQLAlchemy)
    ↓
Database

Request Flow

  1. Controller: Receives the request, extracts parameters, performs basic validation
  2. Service: Applies business logic (checking duplicate emails, permissions, etc.)
  3. Repository: Executes database queries
  4. Model: Defines the data structure
  5. Response: Controller returns JSON to the client

🧪 Testing

To run tests (when implemented):

pytest tests/

📦 Production Deployment

Production Configuration

  1. Change FLASK_ENV=production in .env
  2. Use a robust database (PostgreSQL recommended)
  3. Set a secure SECRET_KEY
  4. Use Gunicorn or uWSGI as WSGI server
  5. Configure Nginx as reverse proxy

Example with Gunicorn

pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 "run:app"

🤝 Contributing

Contributions are welcome. Please:

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

📄 License

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

👥 Authors

🙏 Acknowledgments

  • To the Flask community for excellent tools
  • To SQLAlchemy and Marshmallow contributors

📧 Contact

If you have questions or suggestions, feel free to contact me:


⭐ If this project was helpful to you, don't forget to give it a star on GitHub ⭐


🎯 Summary of Useful Commands

# Installation
python -m venv venv
source venv/bin/activate  # (macOS/Linux)
pip install -r requirements.txt

# Database migrations
flask db init
flask db migrate -m "message"
flask db upgrade
flask db downgrade
python setup_db.py --init

# Run
flask run
python run.py

# Check endpoints
curl http://localhost:5000/api/health