Skip to content

Jakkapan-a/Basic-fastapi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastAPI with SQL Server and JWT Authentication

FastAPI application with SQLAlchemy ORM, SQL Server connection, and JWT (JSON Web Token) authentication.

Features

  • Modern FastAPI framework with automatic API documentation
  • User registration and authentication
  • JWT access tokens and refresh tokens
  • SQL Server database integration
  • RESTful API endpoints with OpenAPI/Swagger docs
  • Type hints and Pydantic models
  • Async support
  • CORS middleware
  • User profile management
  • Token validation and refresh

Project Structure

app/
├── models/
│   └── user.py          # SQLAlchemy User model with token fields
├── routes/
│   └── auth_routes.py   # FastAPI authentication endpoints
├── services/
│   ├── auth_service.py  # Authentication business logic
│   └── jwt_service.py   # JWT token management
├── schemas.py           # Pydantic models for request/response
├── dependencies.py      # FastAPI dependencies for authentication
├── __init__.py          # FastAPI app factory
└── database.py          # Database configuration

Setup

  1. Install dependencies:

    pip install -r requirements.txt
  2. Configure database:

    • Copy .env.example to .env
    • Update DATABASE_URL with your SQL Server connection string
    • Set JWT_SECRET_KEY for token signing
  3. Run the application:

    python serve.py

    Or using uvicorn directly:

    uvicorn serve:app --host 0.0.0.0 --port 8000 --reload
  4. Access API documentation:

API Endpoints

Authentication

  • POST /api/auth/register - Register new user
  • POST /api/auth/login - Login and get JWT tokens
  • POST /api/auth/refresh - Refresh access token using refresh token
  • POST /api/auth/logout - Logout and revoke tokens
  • GET /api/auth/profile - Get user profile (requires JWT token)
  • PUT /api/auth/profile - Update user profile (requires JWT token)
  • GET /api/auth/users - Get all users (requires JWT token)
  • POST /api/auth/validate-token - Validate JWT token (fast validation)
  • GET /api/auth/token-info - Get information about current JWT token

Example Usage

Register a new user:

curl -X POST http://localhost:8000/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "email": "test@example.com",
    "password": "password123",
    "first_name": "Test",
    "last_name": "User"
  }'

Login:

curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "password": "password123"
  }'

Access protected endpoint:

curl -X GET http://localhost:8000/api/auth/profile \
  -H "Authorization: Bearer YOUR_JWT_ACCESS_TOKEN"

Validate JWT token:

curl -X POST http://localhost:8000/api/auth/validate-token \
  -H "Content-Type: application/json" \
  -d '{
    "token": "YOUR_JWT_ACCESS_TOKEN"
  }'

Refresh token:

curl -X POST http://localhost:8000/api/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "YOUR_JWT_REFRESH_TOKEN"
  }'

Database Schema

Users Table

Field Type Description
id Integer Primary key
username String(50) Unique username
email String(100) Unique email
password_hash String(255) Hashed password
first_name String(50) First name
last_name String(50) Last name
is_active Boolean Account status
access_token Text Current access token
refresh_token Text Current refresh token
token_expires_at DateTime Access token expiration
refresh_token_expires_at DateTime Refresh token expiration
created_at DateTime Account creation date
updated_at DateTime Last update date
last_login_at DateTime Last login date

JWT Token Management

  • Access tokens: JWT tokens with 1 hour expiration
  • Refresh tokens: JWT tokens with 30 day expiration
  • Token Structure: Contains user information (user_id, username, email, etc.)
  • Security: HMAC SHA256 algorithm for signing
  • Validation: Fast token validation without database lookup available
  • Revocation: Tokens can be revoked by removing from database

JWT Token Payload

Access Token contains:

  • user_id: User's database ID
  • username: User's username
  • email: User's email
  • first_name: User's first name
  • last_name: User's last name
  • is_active: User's active status
  • type: "access"
  • exp: Expiration timestamp
  • iat: Issued at timestamp
  • nbf: Not before timestamp

Refresh Token contains:

  • user_id: User's database ID
  • username: User's username
  • type: "refresh"
  • exp: Expiration timestamp
  • iat: Issued at timestamp
  • nbf: Not before timestamp

Requirements

  • Python 3.7+
  • SQL Server
  • ODBC Driver 17 for SQL Server
  • FastAPI and Uvicorn for ASGI server
  • PyJWT library for JWT token handling
  • Pydantic for data validation

FastAPI Advantages

  • Automatic API Documentation: Swagger UI and ReDoc available at /docs and /redoc
  • Type Safety: Full type hints support with Pydantic models
  • Performance: High performance, on par with NodeJS and Go
  • Modern Python: Uses modern Python features (Python 3.6+ type hints)
  • Standards-based: Based on OpenAPI and JSON Schema
  • Async Support: Native async/await support
  • Dependency Injection: Advanced dependency injection system
  • Data Validation: Automatic request/response validation

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages