Skip to content

Latest commit

Β 

History

History
250 lines (194 loc) Β· 5.79 KB

File metadata and controls

250 lines (194 loc) Β· 5.79 KB

FastAPI Blog Project

A RESTful Blog API built with FastAPI, SQLAlchemy, and JWT Authentication.

Features

  • πŸ” JWT Authentication - Secure token-based authentication
  • πŸ‘€ User Management - Create, read, update, delete users
  • πŸ“ Blog Management - Full CRUD operations for blog posts
  • πŸ”’ Authorization - Users can only modify their own data
  • πŸ“š API Documentation - Auto-generated Swagger UI and ReDoc
  • πŸ§ͺ Testing - Comprehensive test suite with pytest

Project Structure

FastAPI_Blog_Project/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ api/v1/routes/      # API route handlers
β”‚   β”‚   β”œβ”€β”€ auth.py         # Authentication endpoints
β”‚   β”‚   β”œβ”€β”€ blog.py         # Blog endpoints
β”‚   β”‚   └── user.py         # User endpoints
β”‚   β”œβ”€β”€ core/               # Core configurations
β”‚   β”‚   β”œβ”€β”€ config.py       # Settings management
β”‚   β”‚   β”œβ”€β”€ database.py     # Database connection
β”‚   β”‚   └── security.py     # JWT & password utilities
β”‚   β”œβ”€β”€ models/             # SQLAlchemy models
β”‚   β”œβ”€β”€ schemas/            # Pydantic schemas
β”‚   └── services/           # Business logic
β”œβ”€β”€ migrations/             # Alembic migrations
β”œβ”€β”€ tests/                  # Test suite
└── .env                    # Environment variables

Setup

Prerequisites

  • Python 3.10+
  • MySQL server running on localhost:3306
  • Database blog_db created

Installation

  1. Clone the repository:
git clone <repository-url>
cd FastAPI_Blog_Project
  1. Create and activate virtual environment:
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt
  1. Configure environment variables - create a .env file:
DATABASE_URL=mysql+pymysql://user:password@localhost:3306/blog_db
SECRET_KEY="your-secret-key-here"
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

Tip: Generate a secure secret key with: openssl rand -base64 32

  1. Run database migrations:
alembic upgrade head

Running the Application

Development Server

fastapi dev

Production Server

fastapi run

The API will be available at:

  • API: http://127.0.0.1:8000
  • Swagger Docs: http://127.0.0.1:8000/docs
  • ReDoc: http://127.0.0.1:8000/redoc

API Endpoints

Authentication

Method Endpoint Description Auth Required
POST /api/v1.1/auth/login Login and get JWT token ❌

Users

Method Endpoint Description Auth Required
POST /api/v1.1/users/ Create a new user ❌
GET /api/v1.1/users/ Get all users ❌
GET /api/v1.1/users/me Get current user βœ…
GET /api/v1.1/users/{id} Get user by ID ❌
PUT /api/v1.1/users/{id} Update user βœ… (own profile only)
DELETE /api/v1.1/users/{id} Delete user βœ… (own account only)

Blogs

Method Endpoint Description Auth Required
POST /api/v1.1/blogs/ Create a new blog βœ…
GET /api/v1.1/blogs/ Get all blogs ❌
GET /api/v1.1/blogs/{id} Get blog by ID ❌
PUT /api/v1.1/blogs/{id} Update blog βœ…
DELETE /api/v1.1/blogs/{id} Delete blog βœ…

Authentication

Login

curl -X POST "http://127.0.0.1:8000/api/v1.1/auth/login" \
  -d "username=your_email@example.com&password=your_password"

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "bearer"
}

Using the Token

Include the token in the Authorization header:

curl -X GET "http://127.0.0.1:8000/api/v1.1/users/me" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."

Swagger UI Authentication

  1. Go to http://127.0.0.1:8000/docs
  2. Click the Authorize button (πŸ”“)
  3. Enter your email as username and password
  4. Click Authorize
  5. All protected endpoints will now include your token automatically

Alembic Migrations

Generate a New Migration

After making changes to your models:

alembic revision --autogenerate -m "description of changes"

Apply Migrations

Run all pending migrations:

alembic upgrade head

Rollback Migration

Rollback the last migration:

alembic downgrade -1

View Migration History

alembic history

View Current Revision

alembic current

Testing

Run All Tests

pytest

Run with Coverage

pytest --cov=app --cov-report=html

Run Specific Test File

pytest tests/test_users.py
pytest tests/test_blogs.py

Run Specific Test Class

pytest tests/test_users.py::TestAuthentication
pytest tests/test_blogs.py::TestCreateBlog

Run with Verbose Output

pytest -v

Example Usage

Create a User

curl -X POST "http://127.0.0.1:8000/api/v1.1/users/" \
  -H "Content-Type: application/json" \
  -d '{"name": "John Doe", "email": "john@example.com", "password": "securepass123"}'

Login

curl -X POST "http://127.0.0.1:8000/api/v1.1/auth/login" \
  -d "username=john@example.com&password=securepass123"

Create a Blog (Authenticated)

curl -X POST "http://127.0.0.1:8000/api/v1.1/blogs/" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <your-token>" \
  -d '{"title": "My First Blog", "content": "Hello World!", "author_id": 1}'

Get All Blogs

curl -X GET "http://127.0.0.1:8000/api/v1.1/blogs/"

License

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

Author

Vinald - vinald.me