Skip to content

Latest commit

 

History

History
251 lines (194 loc) · 5.73 KB

File metadata and controls

251 lines (194 loc) · 5.73 KB

Simple FastAPI Application

A basic but feature-rich FastAPI application demonstrating common patterns and best practices.

Features

  • 🚀 FastAPI - Modern, fast web framework for building APIs
  • Uvicorn - Lightning-fast ASGI server
  • 📊 Pydantic - Data validation using Python type annotations
  • 📖 Automatic Documentation - Interactive API docs with Swagger UI
  • 🔍 Search Functionality - Search items by name or description
  • 📄 CRUD Operations - Create, Read, Update, Delete operations
  • 🎯 Query Parameters - Pagination, filtering, and search
  • 💾 In-memory Database - Simple storage for demonstration

Project Structure

fastapi-simple-app/
├── main.py              # Main FastAPI application
├── requirements.txt     # Python dependencies
├── README.md           # This file
├── config.py           # Configuration settings
├── .env.example        # Environment variables example
└── run.py              # Alternative way to run the app

Quick Start

Prerequisites

  • Python 3.8 or higher
  • pip (Python package installer)

Installation Steps

  1. Extract the zip file

    unzip fastapi-simple-app.zip
    cd fastapi-simple-app
  2. Create a virtual environment (recommended)

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

    pip install -r requirements.txt
  4. Run the application

    Method 1: Using uvicorn command

    uvicorn main:app --reload

    Method 2: Run the Python file directly

    python main.py

    Method 3: Using the run script

    python run.py
  5. Open your browser

    Navigate to: http://127.0.0.1:8000

API Endpoints

Base URL: http://127.0.0.1:8000

Method Endpoint Description
GET / Welcome message
GET /health Health check
GET /items Get all items (with pagination)
GET /items/{item_id} Get specific item
POST /items Create new item
PUT /items/{item_id} Update existing item
DELETE /items/{item_id} Delete item
GET /search?q=query Search items
GET /items/available Get available items only

Interactive Documentation

FastAPI automatically generates interactive API documentation:

Example Usage

1. Get all items

curl http://127.0.0.1:8000/items

2. Get specific item

curl http://127.0.0.1:8000/items/1

3. Create new item

curl -X POST "http://127.0.0.1:8000/items" \
     -H "Content-Type: application/json" \
     -d '{
       "id": 4,
       "name": "Monitor",
       "price": 299.99,
       "is_available": true,
       "description": "24-inch monitor"
     }'

4. Search items

curl "http://127.0.0.1:8000/search?q=laptop"

5. Update item

curl -X PUT "http://127.0.0.1:8000/items/1" \
     -H "Content-Type: application/json" \
     -d '{
       "price": 899.99,
       "is_available": false
     }'

6. Delete item

curl -X DELETE "http://127.0.0.1:8000/items/3"

Configuration

The application uses default settings, but you can customize them by:

  1. Modifying config.py
  2. Creating a .env file based on .env.example
  3. Setting environment variables

Development

Running in Development Mode

uvicorn main:app --reload --host 0.0.0.0 --port 8000

Running with Custom Port

uvicorn main:app --reload --port 8080

Production Deployment

For production deployment, consider:

  1. Remove --reload flag
  2. Use Gunicorn with Uvicorn workers:
    pip install gunicorn
    gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker
  3. Set up reverse proxy (Nginx, Apache)
  4. Use environment variables for configuration
  5. Implement proper logging
  6. Add authentication/authorization

Troubleshooting

Common Issues

  1. Port already in use

    Error: [Errno 48] Address already in use
    

    Solution: Use a different port or kill the process using port 8000

    uvicorn main:app --reload --port 8001
  2. ModuleNotFoundError

    ModuleNotFoundError: No module named 'fastapi'
    

    Solution: Make sure you've activated your virtual environment and installed dependencies

    pip install -r requirements.txt
  3. Virtual environment issues

    # Deactivate current environment
    deactivate
    
    # Recreate virtual environment
    rm -rf venv
    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    pip install -r requirements.txt

Testing the API

You can test the API using:

  • Browser - Visit http://127.0.0.1:8000/docs for interactive testing
  • curl - Command line HTTP client
  • Postman - GUI HTTP client
  • httpx or requests - Python HTTP libraries

Next Steps

This is a basic application. To extend it, consider:

  • Adding database integration (SQLAlchemy, MongoDB)
  • Implementing authentication (JWT, OAuth2)
  • Adding input validation and error handling
  • Creating unit tests
  • Adding logging and monitoring
  • Implementing caching
  • Adding rate limiting
  • Creating Docker containers

License

This project is provided as-is for educational purposes.

Support

If you encounter any issues:

  1. Check the troubleshooting section
  2. Ensure all dependencies are installed correctly
  3. Verify Python version compatibility
  4. Check FastAPI documentation: https://fastapi.tiangolo.com/

Happy coding! 🚀