2025-06-03 10:42:03 +00:00

7.3 KiB

Blogging API

A RESTful API for a blogging platform built with FastAPI and SQLite.

Features

  • User management with authentication
  • Blog post creation, retrieval, updating, and deletion
  • Comment functionality on blog posts
  • Role-based permissions (regular users and superusers)
  • RESTful API with proper HTTP methods and status codes
  • JWT-based authentication
  • SQLite database with SQLAlchemy ORM
  • Alembic for database migrations

Prerequisites

  • Python 3.8+
  • Virtual environment (recommended)

Environment Variables

The application uses the following environment variables (see .env.example for a template):

  • SECRET_KEY: Secret key for JWT token encryption (default provided for development)
  • ACCESS_TOKEN_EXPIRE_MINUTES: JWT token expiration time in minutes (default: 60 * 24 * 8 = 8 days)
  • PORT: Port number for the application to listen on (default: 8000)
  • USE_IN_MEMORY_DB: Set to "true" to use an in-memory SQLite database (useful for testing or when file access is problematic)
  • LOG_LEVEL: Logging level (e.g., DEBUG, INFO, WARNING, ERROR) - defaults to INFO

Installation

  1. Clone the repository:
git clone <repository-url>
cd bloggingapi
  1. Install the dependencies:
pip install -r requirements.txt
  1. Run database migrations:
alembic upgrade head
  1. Run the application:
# Development mode
uvicorn main:app --reload

# Production mode
cp .env.example .env  # Create and customize your .env file
python -m uvicorn main:app --host 0.0.0.0 --port 8000

The API will be available at http://localhost:8000.

API Documentation

Once the application is running, you can access the API documentation at:

API Endpoints

Authentication

  • POST /api/v1/login/access-token - Get JWT access token

Users

  • GET /api/v1/users/ - Get all users (superuser only)
  • POST /api/v1/users/ - Create a new user
  • GET /api/v1/users/me - Get current user
  • PUT /api/v1/users/me - Update current user
  • GET /api/v1/users/{user_id} - Get user by ID
  • DELETE /api/v1/users/{user_id} - Delete user (superuser only)

Posts

  • GET /api/v1/posts/ - Get all published posts
  • POST /api/v1/posts/ - Create a new post
  • GET /api/v1/posts/{post_id} - Get post by ID
  • PUT /api/v1/posts/{post_id} - Update post
  • DELETE /api/v1/posts/{post_id} - Delete post
  • GET /api/v1/posts/user/{user_id} - Get posts by user

Comments

  • GET /api/v1/comments/ - Get all comments (superuser only)
  • POST /api/v1/comments/ - Create a new comment
  • GET /api/v1/comments/{comment_id} - Get comment by ID
  • PUT /api/v1/comments/{comment_id} - Update comment
  • DELETE /api/v1/comments/{comment_id} - Delete comment
  • GET /api/v1/comments/post/{post_id} - Get comments by post
  • GET /api/v1/comments/user/{user_id} - Get comments by user

Health Check

  • GET /health - API health check

Project Structure

.
├── .env.example                   # Environment variables template
├── alembic.ini                    # Alembic configuration
├── app                            # Application package
│   ├── api                        # API endpoints
│   │   └── v1                     # API version 1
│   │       ├── api.py             # API router
│   │       └── endpoints          # API endpoint modules
│   │           ├── comments.py    # Comment endpoints
│   │           ├── login.py       # Authentication endpoints
│   │           ├── posts.py       # Post endpoints
│   │           └── users.py       # User endpoints
│   ├── auth                       # Authentication package
│   │   ├── deps.py                # Auth dependencies
│   │   └── security.py            # Security utilities
│   ├── core                       # Core package
│   │   ├── config.py              # Configuration settings
│   │   └── logging.py             # Logging configuration
│   ├── crud                       # CRUD operations
│   │   ├── base.py                # Base CRUD class
│   │   ├── comment.py             # Comment CRUD
│   │   ├── post.py                # Post CRUD
│   │   └── user.py                # User CRUD
│   ├── db                         # Database package
│   │   ├── base.py                # Import all models
│   │   ├── base_class.py          # Base model class
│   │   └── session.py             # Database session
│   ├── models                     # SQLAlchemy models
│   │   ├── comment.py             # Comment model
│   │   ├── post.py                # Post model
│   │   └── user.py                # User model
│   └── schemas                    # Pydantic schemas
│       ├── comment.py             # Comment schemas
│       ├── post.py                # Post schemas
│       └── user.py                # User schemas
├── main.py                        # FastAPI application
├── migrations                     # Alembic migrations
│   ├── env.py                     # Alembic environment
│   ├── script.py.mako             # Migration script template
│   └── versions                   # Migration versions
│       └── 001_initial_tables.py  # Initial migration
└── requirements.txt               # Project dependencies

Development

The project uses Alembic for database migrations. To create a new migration after model changes:

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

To apply migrations:

alembic upgrade head

Running in Production

For production environments, you may want to use a process manager like systemd, PM2, or Docker to manage the application. Here's an example of running the application in the background using nohup:

nohup python -m uvicorn main:app --host 0.0.0.0 --port 8000 --log-level info > app.log 2>&1 &

To view logs:

tail -f app.log  # Application logs

Troubleshooting

If you encounter issues with the application starting up:

  1. Check the application logs where you redirected the output
  2. Verify the database path is correct and accessible
  3. Ensure all environment variables are properly set
  4. Check permissions for the storage directory
  5. Try using the in-memory database option for testing: USE_IN_MEMORY_DB=true
  6. Run the application directly with uvicorn to see detailed error messages: python -m uvicorn main:app --log-level debug
  7. Check your Python environment and installed packages: pip list

Common Issues and Solutions

Database Access Problems

If you encounter database access issues, you can set USE_IN_MEMORY_DB=true in your .env file to use an in-memory SQLite database instead of a file-based one. This can help isolate whether the issue is with file permissions or database configuration.

Process Management

If you're using a process manager (like systemd, PM2, etc.) and encounter issues:

  • Make sure all paths are correctly configured
  • Check that the PYTHONPATH environment variable is set correctly
  • Verify that the process manager has permission to run the application
  • Use python -m uvicorn instead of just uvicorn to ensure the Python module path is correct