Skip to content

dacharyc/test-prompt-fastapi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FastAPI MongoDB Application

A production-ready FastAPI application with MongoDB using the PyMongo driver (Motor for async operations).

Features

  • ✅ FastAPI 0.117+ with async/await
  • ✅ MongoDB with Motor (async PyMongo driver)
  • ✅ Pydantic v2 for data validation
  • ✅ CRUD operations for User resource
  • ✅ RESTful API design
  • ✅ Connection pooling and error handling
  • ✅ CORS middleware
  • ✅ Environment-based configuration
  • ✅ Type hints throughout
  • ✅ Proper HTTP status codes
  • ✅ API documentation (Swagger/ReDoc)

Project Structure

project-name/
├── app/
│   ├── __init__.py
│   ├── config/
│   │   ├── __init__.py
│   │   ├── database.py          # Database connection management
│   │   └── settings.py          # Application settings
│   ├── middleware/
│   │   ├── __init__.py
│   │   └── error_handler.py     # Error handling middleware
│   ├── models/
│   │   ├── __init__.py
│   │   └── user.py              # User model with CRUD operations
│   ├── routers/
│   │   ├── __init__.py
│   │   └── users.py             # User API endpoints
│   └── schemas/
│       ├── __init__.py
│       └── user.py              # Pydantic schemas
├── .env.example                 # Example environment variables
├── .gitignore
├── requirements.txt             # Python dependencies
├── README.md
└── main.py                      # Application entry point

Requirements

  • Python 3.11+
  • MongoDB 4.4+

Installation

  1. Clone the repository
git clone <repository-url>
cd test-prompt-fastapi
  1. Create a virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies
pip install -r requirements.txt
  1. Set up environment variables

Copy .env.example to .env and update the values:

cp .env.example .env

Edit .env:

DEBUG=false
MONGODB_URI=mongodb://localhost:27017
DATABASE_NAME=app_db
CORS_ORIGINS=["http://localhost:3000"]
  1. Start MongoDB

Make sure MongoDB is running on your system. If using Docker:

docker run -d -p 27017:27017 --name mongodb mongo:latest

Running the Application

Development Mode

python main.py

Or with uvicorn directly:

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

Production Mode

uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

The application will be available at:

API Endpoints

Root Endpoints

  • GET / - Welcome message
  • GET /health - Health check endpoint

User Endpoints

All user endpoints are prefixed with /api/v1/users

Create User

POST /api/v1/users
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com"
}

Response (201 Created):

{
  "id": "507f1f77bcf86cd799439011",
  "name": "John Doe",
  "email": "john@example.com",
  "created_at": "2023-01-01T00:00:00Z",
  "updated_at": "2023-01-01T00:00:00Z"
}

Get All Users

GET /api/v1/users?skip=0&limit=100

Response (200 OK):

[
  {
    "id": "507f1f77bcf86cd799439011",
    "name": "John Doe",
    "email": "john@example.com",
    "created_at": "2023-01-01T00:00:00Z",
    "updated_at": "2023-01-01T00:00:00Z"
  }
]

Get User by ID

GET /api/v1/users/{user_id}

Response (200 OK):

{
  "id": "507f1f77bcf86cd799439011",
  "name": "John Doe",
  "email": "john@example.com",
  "created_at": "2023-01-01T00:00:00Z",
  "updated_at": "2023-01-01T00:00:00Z"
}

Update User

PUT /api/v1/users/{user_id}
Content-Type: application/json

{
  "name": "Jane Doe",
  "email": "jane@example.com"
}

Response (200 OK):

{
  "id": "507f1f77bcf86cd799439011",
  "name": "Jane Doe",
  "email": "jane@example.com",
  "created_at": "2023-01-01T00:00:00Z",
  "updated_at": "2023-01-01T00:05:00Z"
}

Delete User

DELETE /api/v1/users/{user_id}

Response (200 OK):

{
  "message": "User deleted successfully"
}

Error Responses

400 Bad Request

{
  "detail": "Invalid user ID format"
}

404 Not Found

{
  "detail": "User not found"
}

500 Internal Server Error

{
  "detail": "Internal server error"
}

Testing with cURL

Create a user

curl -X POST "http://localhost:8000/api/v1/users" \
  -H "Content-Type: application/json" \
  -d '{"name": "John Doe", "email": "john@example.com"}'

Get all users

curl "http://localhost:8000/api/v1/users"

Get user by ID

curl "http://localhost:8000/api/v1/users/{user_id}"

Update user

curl -X PUT "http://localhost:8000/api/v1/users/{user_id}" \
  -H "Content-Type: application/json" \
  -d '{"name": "Jane Doe"}'

Delete user

curl -X DELETE "http://localhost:8000/api/v1/users/{user_id}"

Architecture

Database Connection

The application uses Motor (async PyMongo) for MongoDB operations:

  • Connection pooling with max 10 connections
  • Automatic connection management via FastAPI lifespan events
  • Proper error handling for connection failures

Data Validation

Pydantic v2 models ensure:

  • Type safety
  • Email validation
  • Field constraints (min/max length)
  • Automatic data serialization

Error Handling

Custom exception handlers for:

  • MongoDB duplicate key errors
  • Invalid ObjectId format
  • General exceptions

Development

Code Style

  • Modern Python with type hints
  • Async/await syntax throughout
  • FastAPI dependency injection
  • Pydantic models for validation

Adding New Resources

  1. Create schema in app/schemas/
  2. Create model in app/models/
  3. Create router in app/routers/
  4. Register router in main.py

License

MIT License

About

Temp repo to test a prompt to generate a FastAPI/MongoDB app.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages