Skip to content

rfpga/fastapi-aws

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastAPI Learning Guide - From Beginner to Advanced

Table of Contents

  1. What is FastAPI?
  2. Project Structure Overview
  3. Core Concepts
  4. Hands-on Learning Path
  5. Advanced Topics
  6. Best Practices

What is FastAPI?

FastAPI is a modern, fast web framework for building APIs with Python based on standard Python type hints. It's designed to be:

  • Fast: High performance, on par with NodeJS and Go
  • Easy: Simple to learn and use
  • Robust: Production-ready code with automatic interactive documentation

Project Structure Overview

Your project follows a well-organized structure that separates concerns:

fastapi-aws/
├── api/
│   ├── __init__.py
│   ├── main.py              # Main application entry point
│   ├── models.py            # Database models (SQLAlchemy)
│   ├── dependencies/
│   │   └── deps.py          # Shared dependencies (auth, database)
│   └── routers/
│       ├── auth.py          # Authentication endpoints
│       ├── dogs.py          # Dog-related endpoints
│       ├── comments.py      # Comment endpoints
│       └── posts.py         # Post endpoints
├── requirements.txt         # Python dependencies
├── .env-sample             # Environment variables template
└── Procfile                # Deployment configuration

Core Concepts

1. Application Instance (main.py)

from fastapi import FastAPI
app = FastAPI()  # This creates your API application

Key Learning Points:

  • The FastAPI() instance is your entire application
  • CORS middleware handles cross-origin requests
  • Routers are included to organize endpoints

2. Path Operations (HTTP Methods)

FastAPI uses decorators to define endpoints:

@app.get("/")           # GET request
@app.post("/dogs")      # POST request  
@app.put("/dogs/{id}")  # PUT request
@app.delete("/dogs/{id}")  # DELETE request

3. Pydantic Models (Data Validation)

Pydantic models define the structure and validation of your data:

class DogCreateRequest(BaseModel):
    name: str
    breed: str 
    age: int

Why this matters:

  • Automatic validation of incoming data
  • Auto-generated API documentation
  • Type safety

4. Dependency Injection

Dependencies are reusable components that can be injected into your endpoints:

# From deps.py
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# Usage in endpoint
@router.get("/dogs")
def get_dogs(db: db_dependency):  # db_dependency = Annotated[Session, Depends(get_db)]
    return db.query(Dog).all()

Hands-on Learning Path

Phase 1: Understanding the Basics (Start Here)

Step 1: Examine the Main Application (main.py)

Learning Goals: Understand app creation, middleware, and routing

Exercise:

  1. Look at how the FastAPI app is created
  2. Notice the CORS middleware configuration
  3. See how routers are included

Key Code to Study:

app = FastAPI()
app.add_middleware(CORSMiddleware, ...)
app.include_router(auth.router)

Step 2: Simple Endpoints (dogs.py)

Learning Goals: Basic CRUD operations

Start with these endpoints:

@router.get("/userdogs")  # Read user's dogs
@router.post("/")         # Create a dog
@router.delete("/{dog_id}")  # Delete a dog

Exercise:

  1. Trace how a GET request flows through the code
  2. Understand how user authentication is checked
  3. See how database operations work

Step 3: Data Models (models.py)

Learning Goals: Database integration with SQLAlchemy

Key Concepts:

  • Table definitions using SQLAlchemy ORM
  • Relationships between tables (User → Dogs, Posts, etc.)
  • Database engine and session management

Phase 2: Intermediate Concepts

Step 4: Authentication System (auth.py)

Learning Goals: JWT authentication, password hashing

Study Flow:

  1. User registration → Password hashing with bcrypt
  2. User login → JWT token generation
  3. Protected endpoints → Token validation

Key Code:

def authenticate_user(username: str, password: str, db):
    # Password verification logic
    
def create_access_token(username: str, user_id: int, expires_delta: timedelta):
    # JWT token creation

Step 5: Dependencies (deps.py)

Learning Goals: Dependency injection patterns

Important Dependencies:

  • get_db(): Database session management
  • get_current_user(): User authentication
  • bcrypt_context: Password hashing

Step 6: Complex Queries (posts.py)

Learning Goals: Advanced database operations, pagination

Study the posts endpoint:

  • Joining multiple tables
  • Counting related records
  • Pagination implementation
  • Time formatting logic

Phase 3: Advanced Features

Step 7: Response Models and Schemas

Learning Goals: API response structuring

In posts.py, notice different response models:

  • PostUserResponse: For list views
  • PostSchema: For detailed views with nested data

Step 8: Error Handling

Pattern used throughout:

if not item:
    raise HTTPException(status_code=404, detail="Item not found")

Step 9: Database Relationships

Study how the models relate:

  • User has many Dogs
  • User has many Posts
  • Post has many Comments
  • User has one Image

Practical Exercises

Exercise 1: Create Your First Endpoint

Create a simple health check endpoint:

@app.get("/health")
async def health_check():
    return {"status": "healthy", "timestamp": datetime.now()}

Exercise 2: Add a New Model

Create a "Like" system for posts:

  1. Add a Like model in models.py
  2. Create a likes.py router
  3. Add endpoints to like/unlike posts
  4. Update post responses to include like counts

Exercise 3: Enhance Validation

Add validation to the DogCreateRequest:

  • Age must be between 0 and 25
  • Name must be at least 2 characters
  • Breed from a predefined list

Advanced Topics

1. Async/Await

Some endpoints use async def - this enables handling multiple requests concurrently:

async def get_current_user(token: oauth2_bearer_dependency):
    # Async function for better performance

2. Middleware

CORS middleware in your project handles cross-origin requests:

app.add_middleware(
    CORSMiddleware,
    allow_origins=[os.getenv("API_URL")],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

3. Environment Configuration

Using .env files for configuration:

load_dotenv()
SECRET_KEY = os.getenv("AUTH_SECRET_KEY")

4. Database Session Management

The dependency pattern ensures database connections are properly managed:

def get_db():
    db = SessionLocal()
    try:
        yield db  # Provides database session
    finally:
        db.close()  # Always closes connection

Best Practices Demonstrated in Your Project

1. Separation of Concerns

  • Models in models.py
  • Business logic in routers
  • Shared functionality in dependencies/

2. Type Hints

Every function uses proper type hints:

def create_dog(db: db_dependency, user: user_dependency, dog: DogCreateRequest):

3. Pydantic for Validation

All input/output data is validated using Pydantic models

4. Security

  • JWT tokens for authentication
  • Password hashing with bcrypt
  • User authorization checks

5. Database Best Practices

  • Proper session management
  • Relationship definitions
  • Connection pooling

Next Steps for Learning

  1. Run the Project Locally

    • Set up a virtual environment
    • Install requirements: pip install -r requirements.txt
    • Create a .env file from .env-sample
    • Run: uvicorn api.main:app --reload
  2. Explore the API Documentation

    • Visit http://localhost:8000/docs for interactive Swagger docs
    • Try out different endpoints
  3. Modify and Experiment

    • Add new fields to existing models
    • Create new endpoints
    • Implement new features
  4. Study Real-World Patterns

    • Look at how pagination is implemented
    • Understand the authentication flow
    • See how related data is fetched efficiently

Common FastAPI Patterns in Your Project

Pattern 1: Router Organization

router = APIRouter(prefix='/dogs', tags=['Dogs'])

Pattern 2: Dependency Injection

def endpoint(db: db_dependency, user: user_dependency):

Pattern 3: Response Models

@router.get("/", response_model=List[PostSchema])

Pattern 4: Error Handling

if not item:
    raise HTTPException(status_code=404, detail="Not found")

This project is an excellent example of a production-ready FastAPI application. Take your time with each phase, experiment with the code, and don't hesitate to break things – that's how you learn best!# fastapi-aws

fastapi-aws

fastapi-aws

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors