A production-ready FastAPI application with JWT authentication that enables users to manage tasks securely. Features complete CRUD operations, user authentication, task ownership validation, and advanced filtering capabilities.
β¨ Core Features:
- User registration and secure login with password hashing
- JWT-based authentication for secure endpoints
- Complete CRUD operations for tasks (Create, Read, Update, Delete)
- Task ownership validation (users can only manage their own tasks)
- Advanced filtering and sorting (by date, status, priority)
- Input validation with detailed error messages
- Auto-generated API documentation (Swagger UI & ReDoc)
- Health check endpoint
- Error handling with meaningful responses
π Security Features:
- Password hashing using
passlibwith bcrypt - JWT token-based authentication
- Protected endpoints requiring valid tokens
- User-specific task isolation
- CORS support (configurable)
- Framework: FastAPI
- Authentication: JWT (python-jose, passlib)
- Database: In-memory (easily upgradeable to PostgreSQL/MongoDB)
- Validation: Pydantic
- Server: Uvicorn
- Documentation: Swagger UI, ReDoc
- Python 3.9+
- pip (Python package manager)
- Git (for cloning repository)
git clone https://github.com/YOUR_USERNAME/task-manager-api.git
cd task-manager-api# On Linux/macOS
python3 -m venv venv
source venv/bin/activate
# On Windows
python -m venv venv
venv\Scripts\activatepip install -r requirements.txtFile: .env
SECRET_KEY=your-super-secret-key-change-this
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
Start the development server:
python main.pyThe API will be available at:
- API Base URL:
http://localhost:8000 - Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
POST /auth/register
Content-Type: application/json
{
"username": "john_doe",
"email": "john@example.com",
"password": "securepassword123"
}Response: 201 Created
{
"id": "user_123",
"username": "john_doe",
"email": "john@example.com",
"message": "User registered successfully"
}POST /auth/login
Content-Type: application/json
{
"username": "john_doe",
"password": "securepassword123"
}Response: 200 OK
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer",
"expires_in": 1800
}POST /tasks
Authorization: Bearer <your_token>
Content-Type: application/json
{
"title": "Buy groceries",
"description": "Milk, eggs, bread",
"priority": "high",
"due_date": "2024-03-01"
}Response: 201 Created
{
"id": "task_456",
"user_id": "user_123",
"title": "Buy groceries",
"description": "Milk, eggs, bread",
"priority": "high",
"status": "pending",
"due_date": "2024-03-01",
"created_at": "2024-02-23T10:30:00",
"updated_at": "2024-02-23T10:30:00"
}GET /tasks
Authorization: Bearer <your_token>Query Parameters:
status- Filter by status (pending, completed, in_progress)priority- Filter by priority (low, medium, high)sort_by- Sort by field (due_date, created_at, priority)order- Ascending (asc) or descending (desc)
Example with filters:
GET /tasks?status=pending&priority=high&sort_by=due_date&order=asc
Authorization: Bearer <your_token>Response: 200 OK
{
"total": 2,
"tasks": [
{
"id": "task_456",
"user_id": "user_123",
"title": "Buy groceries",
"description": "Milk, eggs, bread",
"priority": "high",
"status": "pending",
"due_date": "2024-03-01",
"created_at": "2024-02-23T10:30:00",
"updated_at": "2024-02-23T10:30:00"
},
{
"id": "task_789",
"user_id": "user_123",
"title": "Complete project",
"description": "Finish API implementation",
"priority": "high",
"status": "in_progress",
"due_date": "2024-02-28",
"created_at": "2024-02-20T14:15:00",
"updated_at": "2024-02-23T09:00:00"
}
]
}GET /tasks/{task_id}
Authorization: Bearer <your_token>Example:
GET /tasks/task_456
Authorization: Bearer <your_token>Response: 200 OK
{
"id": "task_456",
"user_id": "user_123",
"title": "Buy groceries",
"description": "Milk, eggs, bread",
"priority": "high",
"status": "pending",
"due_date": "2024-03-01",
"created_at": "2024-02-23T10:30:00",
"updated_at": "2024-02-23T10:30:00"
}Error Response: 404 Not Found
{
"detail": "Task not found or access denied"
}PUT /tasks/{task_id}
Authorization: Bearer <your_token>
Content-Type: application/json
{
"title": "Buy groceries and cook",
"description": "Updated description",
"status": "in_progress",
"priority": "medium",
"due_date": "2024-03-02"
}Response: 200 OK
{
"id": "task_456",
"user_id": "user_123",
"title": "Buy groceries and cook",
"description": "Updated description",
"priority": "medium",
"status": "in_progress",
"due_date": "2024-03-02",
"created_at": "2024-02-23T10:30:00",
"updated_at": "2024-02-23T14:45:00"
}DELETE /tasks/{task_id}
Authorization: Bearer <your_token>Response: 200 OK
{
"message": "Task deleted successfully",
"task_id": "task_456"
}PATCH /tasks/{task_id}/status
Authorization: Bearer <your_token>
Content-Type: application/json
{
"status": "completed"
}Allowed statuses: pending, in_progress, completed
Response: 200 OK
{
"id": "task_456",
"status": "completed",
"updated_at": "2024-02-23T15:00:00",
"message": "Task status updated to completed"
}GET /healthResponse: 200 OK
{
"status": "healthy",
"timestamp": "2024-02-23T10:30:00"
}Step 1: Register a User
curl -X POST "http://localhost:8000/auth/register" \
-H "Content-Type: application/json" \
-d '{
"username": "john_doe",
"email": "john@example.com",
"password": "password123"
}'Step 2: Login
curl -X POST "http://localhost:8000/auth/login" \
-H "Content-Type: application/json" \
-d '{
"username": "john_doe",
"password": "password123"
}'Save the returned access_token
Step 3: Create a Task
curl -X POST "http://localhost:8000/tasks" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "Learn FastAPI",
"description": "Complete FastAPI tutorial",
"priority": "high",
"due_date": "2024-03-15"
}'Step 4: Get All Tasks
curl -X GET "http://localhost:8000/tasks" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"Step 5: Update a Task
curl -X PUT "http://localhost:8000/tasks/task_id" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "Learn FastAPI and Deploy",
"status": "in_progress"
}'Step 6: Delete a Task
curl -X DELETE "http://localhost:8000/tasks/task_id" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"The API uses JSON Web Tokens (JWT) for authentication.
Token Format:
Authorization: Bearer <token>
Token Contents:
{
"sub": "user_id",
"username": "john_doe",
"exp": 1708697400
}- Login to get access token
- Include token in
Authorizationheader for protected endpoints - Token expires after 30 minutes (default)
- Request new token by logging in again
Protected Endpoints (Require JWT Token):
POST /tasks- Create taskGET /tasks- Get all tasksGET /tasks/{id}- Get single taskPUT /tasks/{id}- Update taskDELETE /tasks/{id}- Delete taskPATCH /tasks/{id}/status- Update status
Public Endpoints (No Token Required):
POST /auth/register- User registrationPOST /auth/login- User loginGET /health- Health check
task-manager-api/
βββ main.py # Main FastAPI application
βββ requirements.txt # Project dependencies
βββ .env # Environment variables (create yourself)
βββ .gitignore # Git ignore file
βββ README.md # This file
βββ Dockerfile # Docker container configuration
βββ models/
βββ user.py # User data models
βββ task.py # Task data models
{
"id": "string (unique)",
"username": "string (unique)",
"email": "string (unique)",
"hashed_password": "string",
"created_at": "datetime"
}{
"id": "string (unique)",
"user_id": "string (foreign key)",
"title": "string (required, 1-200 chars)",
"description": "string (optional, max 1000 chars)",
"status": "enum: pending | in_progress | completed",
"priority": "enum: low | medium | high",
"due_date": "date (optional)",
"created_at": "datetime (auto-generated)",
"updated_at": "datetime (auto-updated)"
}docker build -t task-manager-api:1.0 .docker run -p 8000:8000 task-manager-api:1.0docker-compose upAccess at: http://localhost:8000
fastapi==0.104.1
uvicorn==0.24.0
pydantic==2.5.0
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-dotenv==1.0.0
Create .env file in project root:
# JWT Configuration
SECRET_KEY=your-super-secret-key-change-this-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
# API Configuration
API_TITLE=Task Manager API
API_VERSION=1.0.0
DEBUG=True- Passwords are hashed using bcrypt algorithm
- Original passwords are never stored in database
- Always hash before comparing:
verify_password(plain_password, hashed_password)
- Tokens are signed with
SECRET_KEY - Each token includes user ID and expiration time
- Tokens must be validated on every protected request
- Each task belongs to one user
- Users can only access/modify their own tasks
- Server validates ownership before returning task data
400 Bad Request- Invalid input401 Unauthorized- Missing or invalid token403 Forbidden- Access denied (not task owner)404 Not Found- Task doesn't exist409 Conflict- Duplicate username/email
- Start API:
python main.py - Open:
http://localhost:8000/docs - Click "Try it out" on any endpoint
- For protected endpoints:
- Register user
- Login to get token
- Click lock icon and paste token
- Test endpoints directly!
- Import API into Postman
- Create environment with
tokenvariable - Login endpoint stores token automatically
- Use
{{token}}in Authorization header - Test all workflows easily
pip install pytest
pytest # Run tests if available# Push to GitHub first
git push origin main
# Then on Railway.app:
1. Create new project
2. Select GitHub repository
3. Set environment variables in Railway dashboard
4. Deploy automatically!1. Connect GitHub account
2. Create new Web Service
3. Select this repository
4. Set Runtime: Python 3.11
5. Set Start Command: uvicorn main:app --host 0.0.0.0 --port 8000
6. Deploy!Solution: Create .env file with SECRET_KEY=your_secret_key
Solution: Login again to get a new token
Solution: Make sure:
- Task ID is correct
- You own the task (created by your user)
- Token is from the correct user
Solution: Make sure API is running (python main.py)
Contributions are welcome! To contribute:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
Your Name
- GitHub: Mukesh-2005
- Email: starmukesh2005@gmail.com
- FastAPI community for the amazing framework
- Python community for excellent libraries
- All contributors and users of this project
For support,starmukesh2005@gmail.com or open an issue on GitHub.
Last Updated: February 23, 2024
Version: 1.0.0
β If you found this helpful, please star the repository!