Skip to content

Israelistic/API_Social_Media_ORM

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 

Repository files navigation

FastAPI Social Media API

A RESTful API for a social media platform built with FastAPI, PostgreSQL, and SQLAlchemy ORM. This API provides endpoints for user management, authentication, and post operations with JWT-based security.

🚀 Features

  • User Management: User registration and profile retrieval
  • Authentication: JWT-based authentication with OAuth2 Bearer tokens
  • Post Management: Full CRUD operations for social media posts
  • Security: Password hashing with bcrypt, JWT token expiration
  • Database: PostgreSQL with SQLAlchemy ORM
  • API Documentation: Auto-generated interactive docs with Swagger UI

📋 Table of Contents

🛠 Technologies

  • FastAPI - Modern, fast web framework for building APIs
  • PostgreSQL - Relational database
  • SQLAlchemy - Python SQL toolkit and ORM
  • Pydantic - Data validation using Python type annotations
  • Passlib - Password hashing library (bcrypt)
  • Python-JOSE - JWT token creation and validation
  • Uvicorn - ASGI server for running the application

📁 Project Structure

API_Social_Media_ORM/
├── app/
│   ├── __init__.py
│   ├── main.py              # Application entry point
│   ├── config.py            # Configuration settings
│   ├── database.py          # Database connection and session
│   ├── models.py            # SQLAlchemy ORM models
│   ├── schemas.py           # Pydantic schemas for validation
│   ├── utils.py             # Utility functions (password hashing)
│   ├── oauth2.py            # JWT authentication logic
│   └── routers/
│       ├── auth.py          # Authentication routes
│       ├── post.py          # Post management routes
│       └── user.py          # User management routes
├── venv/                    # Virtual environment
├── requirements.txt         # Python dependencies
└── README.md               # Project documentation

📦 Installation

Prerequisites

  • Python 3.8+
  • PostgreSQL 12+
  • pip (Python package manager)

Steps

  1. Clone the repository

    git clone <repository-url>
    cd API_Social_Media_ORM
  2. Create and activate virtual environment

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies

    pip install -r app/requirements.txt
  4. Set up PostgreSQL database

    CREATE DATABASE fastapiORM;
  5. Configure environment variables

    Create a .env file in the project root or set environment variables:

    export DB_USER="your_db_user"
    export DB_PASSWORD="your_db_password"

⚙️ Configuration

Database Configuration

The application uses environment variables for database credentials. Set the following:

export DB_USER="your_db_user"
export DB_PASSWORD="your_db_password"

Or create a .env file in the project root:

DB_USER=your_db_user
DB_PASSWORD=your_db_password

The database connection will use the database name fastapiORM.

JWT Configuration

The JWT secret key is configured in app/oauth2.py. For production:

  • Generate a secure random key: openssl rand -hex 32
  • Store it as an environment variable
  • Update SECRET_KEY in oauth2.py

🏃 Running the Application

  1. Activate virtual environment

    source venv/bin/activate
  2. Start the server

    uvicorn app.main:app --reload

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

  3. Access API Documentation

    • Swagger UI: http://localhost:8000/docs
    • ReDoc: http://localhost:8000/redoc

🌐 API Endpoints

Authentication

Method Endpoint Description Authentication
POST /login Login and get JWT token No

Users

Method Endpoint Description Authentication
POST /users Register a new user No
GET /users/{id} Get user by ID No

Posts

Method Endpoint Description Authentication
GET /posts Get all posts Yes
POST /posts Create a new post Yes
GET /posts/{id} Get post by ID Yes
PUT /posts/{id} Update a post Yes
DELETE /posts/{id} Delete a post Yes

🔐 Authentication

This API uses JWT (JSON Web Tokens) for authentication.

Getting a Token

  1. Register a user (POST /users):

    {
      "email": "user@example.com",
      "password": "yourpassword"
    }
  2. Login (POST /login):

    curl -X POST "http://localhost:8000/login" \
      -H "Content-Type: application/x-www-form-urlencoded" \
      -d "username=user@example.com&password=yourpassword"

    Response:

    {
      "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
      "token_type": "Bearer"
    }
  3. Use the token in subsequent requests:

    curl -X GET "http://localhost:8000/posts" \
      -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Token Details

  • Algorithm: HS256 (HMAC-SHA256)
  • Expiration: 30 minutes
  • Header Format: Authorization: Bearer <token>

🗄 Database Schema

Users Table

Column Type Constraints
id INTEGER PRIMARY KEY
email VARCHAR UNIQUE, NOT NULL
password VARCHAR NOT NULL (bcrypt hashed)
created_at TIMESTAMP NOT NULL, DEFAULT now()

Posts Table

Column Type Constraints
id INTEGER PRIMARY KEY
title VARCHAR NOT NULL
content VARCHAR NOT NULL
published BOOLEAN NOT NULL, DEFAULT true
created_at TIMESTAMP NOT NULL, DEFAULT now()

🔧 Development

Code Structure

  • models.py: SQLAlchemy ORM models (database tables)
  • schemas.py: Pydantic models (request/response validation)
  • routers/: Endpoint definitions organized by resource
  • oauth2.py: JWT token creation and validation
  • utils.py: Helper functions (password hashing)
  • database.py: Database connection and session management

Adding New Features

  1. Define the database model in models.py
  2. Create Pydantic schemas in schemas.py
  3. Implement route handlers in routers/
  4. Register the router in main.py

Testing

The API can be tested using:

  • Swagger UI: http://localhost:8000/docs (interactive testing)
  • Postman: Import endpoints and test manually
  • curl: Command-line testing
  • pytest: Unit and integration tests (to be implemented)

📝 API Examples

Create a Post

curl -X POST "http://localhost:8000/posts" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "My First Post",
    "content": "This is the content of my post",
    "published": true
  }'

Get All Posts

curl -X GET "http://localhost:8000/posts" \
  -H "Authorization: Bearer YOUR_TOKEN"

Update a Post

curl -X PUT "http://localhost:8000/posts/1" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Updated Title",
    "content": "Updated content",
    "published": true
  }'

Delete a Post

curl -X DELETE "http://localhost:8000/posts/1" \
  -H "Authorization: Bearer YOUR_TOKEN"

🔒 Security Best Practices

  1. Never commit secrets: Use environment variables for sensitive data
  2. Use HTTPS: In production, always use HTTPS
  3. Rotate JWT secrets: Regularly update your SECRET_KEY
  4. Validate input: Pydantic schemas provide automatic validation
  5. Rate limiting: Consider implementing rate limiting in production
  6. CORS: Configure CORS properly for your frontend domain

📄 License

This project is for educational purposes.

👤 Author

Haggai Lerman

🤝 Contributing

Contributions, issues, and feature requests are welcome!

📞 Support

For support, open an issue in the repository.

About

API implementation using Object Relational M

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages