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.
- 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
- Technologies
- Project Structure
- Installation
- Configuration
- Running the Application
- API Endpoints
- Authentication
- Database Schema
- Development
- 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
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
- Python 3.8+
- PostgreSQL 12+
- pip (Python package manager)
-
Clone the repository
git clone <repository-url> cd API_Social_Media_ORM
-
Create and activate virtual environment
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r app/requirements.txt
-
Set up PostgreSQL database
CREATE DATABASE fastapiORM;
-
Configure environment variables
Create a
.envfile in the project root or set environment variables:export DB_USER="your_db_user" export DB_PASSWORD="your_db_password"
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_passwordThe database connection will use the database name fastapiORM.
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_KEYinoauth2.py
-
Activate virtual environment
source venv/bin/activate -
Start the server
uvicorn app.main:app --reload
The API will be available at:
http://localhost:8000 -
Access API Documentation
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
- Swagger UI:
| Method | Endpoint | Description | Authentication |
|---|---|---|---|
| POST | /login |
Login and get JWT token | No |
| Method | Endpoint | Description | Authentication |
|---|---|---|---|
| POST | /users |
Register a new user | No |
| GET | /users/{id} |
Get user by ID | No |
| 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 |
This API uses JWT (JSON Web Tokens) for authentication.
-
Register a user (POST
/users):{ "email": "user@example.com", "password": "yourpassword" } -
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" } -
Use the token in subsequent requests:
curl -X GET "http://localhost:8000/posts" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
- Algorithm: HS256 (HMAC-SHA256)
- Expiration: 30 minutes
- Header Format:
Authorization: Bearer <token>
| Column | Type | Constraints |
|---|---|---|
| id | INTEGER | PRIMARY KEY |
| VARCHAR | UNIQUE, NOT NULL | |
| password | VARCHAR | NOT NULL (bcrypt hashed) |
| created_at | TIMESTAMP | NOT NULL, DEFAULT now() |
| 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() |
- 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
- Define the database model in
models.py - Create Pydantic schemas in
schemas.py - Implement route handlers in
routers/ - Register the router in
main.py
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)
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
}'curl -X GET "http://localhost:8000/posts" \
-H "Authorization: Bearer YOUR_TOKEN"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
}'curl -X DELETE "http://localhost:8000/posts/1" \
-H "Authorization: Bearer YOUR_TOKEN"- Never commit secrets: Use environment variables for sensitive data
- Use HTTPS: In production, always use HTTPS
- Rotate JWT secrets: Regularly update your SECRET_KEY
- Validate input: Pydantic schemas provide automatic validation
- Rate limiting: Consider implementing rate limiting in production
- CORS: Configure CORS properly for your frontend domain
This project is for educational purposes.
Haggai Lerman
Contributions, issues, and feature requests are welcome!
For support, open an issue in the repository.