Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“ Task Manager API

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.

🎯 Features

✨ 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 passlib with bcrypt
  • JWT token-based authentication
  • Protected endpoints requiring valid tokens
  • User-specific task isolation
  • CORS support (configurable)

πŸ“‹ Tech Stack

  • Framework: FastAPI
  • Authentication: JWT (python-jose, passlib)
  • Database: In-memory (easily upgradeable to PostgreSQL/MongoDB)
  • Validation: Pydantic
  • Server: Uvicorn
  • Documentation: Swagger UI, ReDoc

πŸ“¦ Prerequisites

  • Python 3.9+
  • pip (Python package manager)
  • Git (for cloning repository)

πŸš€ Installation & Setup

1. Clone the Repository

git clone https://github.com/YOUR_USERNAME/task-manager-api.git
cd task-manager-api

2. Create Virtual Environment

# On Linux/macOS
python3 -m venv venv
source venv/bin/activate

# On Windows
python -m venv venv
venv\Scripts\activate

3. Install Dependencies

pip install -r requirements.txt

4. Create .env File (Optional)

File: .env

SECRET_KEY=your-super-secret-key-change-this
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

πŸƒ Running the API

Start the development server:

python main.py

The API will be available at:

  • API Base URL: http://localhost:8000
  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

πŸ“‘ API Endpoints

Authentication Endpoints

1. User Registration

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"
}

2. User Login

POST /auth/login
Content-Type: application/json

{
  "username": "john_doe",
  "password": "securepassword123"
}

Response: 200 OK

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 1800
}

Task Endpoints

3. Create a New Task ✨

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"
}

4. Get All Tasks (for Current User)

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"
    }
  ]
}

5. Get Single Task

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"
}

6. Update Task

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"
}

7. Delete Task

DELETE /tasks/{task_id}
Authorization: Bearer <your_token>

Response: 200 OK

{
  "message": "Task deleted successfully",
  "task_id": "task_456"
}

8. Update Task Status

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"
}

System Endpoints

9. Health Check

GET /health

Response: 200 OK

{
  "status": "healthy",
  "timestamp": "2024-02-23T10:30:00"
}

πŸ§ͺ Testing with cURL

Complete Workflow Example

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"

πŸ” Authentication Details

JWT Token Structure

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

Token Format:

Authorization: Bearer <token>

Token Contents:

{
  "sub": "user_id",
  "username": "john_doe",
  "exp": 1708697400
}

How to Use JWT Token

  1. Login to get access token
  2. Include token in Authorization header for protected endpoints
  3. Token expires after 30 minutes (default)
  4. Request new token by logging in again

Protected vs Public Endpoints

Protected Endpoints (Require JWT Token):

  • POST /tasks - Create task
  • GET /tasks - Get all tasks
  • GET /tasks/{id} - Get single task
  • PUT /tasks/{id} - Update task
  • DELETE /tasks/{id} - Delete task
  • PATCH /tasks/{id}/status - Update status

Public Endpoints (No Token Required):

  • POST /auth/register - User registration
  • POST /auth/login - User login
  • GET /health - Health check

πŸ“ Project Structure

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

πŸ“Š Data Models

User Model

{
  "id": "string (unique)",
  "username": "string (unique)",
  "email": "string (unique)",
  "hashed_password": "string",
  "created_at": "datetime"
}

Task Model

{
  "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 Setup

Build Docker Image

docker build -t task-manager-api:1.0 .

Run with Docker

docker run -p 8000:8000 task-manager-api:1.0

Using Docker Compose

docker-compose up

Access at: http://localhost:8000


πŸ“‹ requirements.txt

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

βš™οΈ Configuration

Environment Variables

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

🧠 Key Implementation Details

Password Security

  • Passwords are hashed using bcrypt algorithm
  • Original passwords are never stored in database
  • Always hash before comparing: verify_password(plain_password, hashed_password)

JWT Authentication

  • Tokens are signed with SECRET_KEY
  • Each token includes user ID and expiration time
  • Tokens must be validated on every protected request

Task Ownership

  • Each task belongs to one user
  • Users can only access/modify their own tasks
  • Server validates ownership before returning task data

Error Handling

  • 400 Bad Request - Invalid input
  • 401 Unauthorized - Missing or invalid token
  • 403 Forbidden - Access denied (not task owner)
  • 404 Not Found - Task doesn't exist
  • 409 Conflict - Duplicate username/email

πŸ§ͺ Testing Tips

Using Swagger UI (Recommended)

  1. Start API: python main.py
  2. Open: http://localhost:8000/docs
  3. Click "Try it out" on any endpoint
  4. For protected endpoints:
    • Register user
    • Login to get token
    • Click lock icon and paste token
    • Test endpoints directly!

Using Postman

  1. Import API into Postman
  2. Create environment with token variable
  3. Login endpoint stores token automatically
  4. Use {{token}} in Authorization header
  5. Test all workflows easily

Unit Testing (Optional)

pip install pytest
pytest  # Run tests if available

πŸš€ Deployment

Deploy to Railway.app

# 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!

Deploy to Render.com

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!

πŸ” Troubleshooting

Issue: "Secret key not found"

Solution: Create .env file with SECRET_KEY=your_secret_key

Issue: "Token invalid or expired"

Solution: Login again to get a new token

Issue: "Task not found"

Solution: Make sure:

  • Task ID is correct
  • You own the task (created by your user)
  • Token is from the correct user

Issue: "Connection refused"

Solution: Make sure API is running (python main.py)


πŸ“š Learning Resources


🀝 Contributing

Contributions are welcome! To contribute:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ License

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


πŸ‘¨β€πŸ’» Author

Your Name


πŸ™Œ Acknowledgments

  • FastAPI community for the amazing framework
  • Python community for excellent libraries
  • All contributors and users of this project

πŸ“ž Support

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!

About

Complete Task Manager API with authentication and CRUD operations. Working authentication system with JWT tokens

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages