-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2 from FahimFBA/f-branch-1
Complete API Backend with FastAPI & MongoDB
- Loading branch information
Showing
6 changed files
with
529 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
""" | ||
MongoDB Database Initialization Module | ||
This module is responsible for initializing the MongoDB database connection, | ||
creating necessary indexes, and setting up the database for the Vehicle Allocation System. | ||
""" | ||
|
||
from motor.motor_asyncio import AsyncIOMotorClient | ||
from dotenv import load_dotenv | ||
import os | ||
import asyncio | ||
|
||
# Load environment variables from .env file | ||
load_dotenv() | ||
|
||
# Retrieve the MongoDB credentials from the environment variables | ||
username = os.getenv("MONGO_USERNAME") | ||
password = os.getenv("MONGO_PASSWORD") | ||
cluster = os.getenv("MONGO_CLUSTER_URL") | ||
|
||
# Create the MongoDB connection URI using the loaded credentials | ||
uri = f"mongodb+srv://{username}:{password}@{ | ||
cluster}/?retryWrites=true&w=majority&appName=Cluster0" | ||
|
||
# Initialize MongoDB client and access the database | ||
client = AsyncIOMotorClient(uri) | ||
db = client.vallocation_db | ||
collection = db.vallocation_collection | ||
|
||
# Function to create indexes | ||
async def create_indexes(): | ||
""" | ||
Create necessary indexes in the MongoDB collection. | ||
Indexes: | ||
- Unique index on 'vehicle_id' and 'allocation_date' to prevent double booking | ||
- Index on 'employee_id' for efficient querying | ||
""" | ||
await collection.create_index([("vehicle_id", 1), ("allocation_date", 1)], unique=True) | ||
await collection.create_index([("employee_id", 1)]) | ||
|
||
# Function to initialize the database at startup | ||
async def initialize_db(): | ||
""" | ||
Initialize the MongoDB database by creating necessary indexes. | ||
""" | ||
await create_indexes() | ||
|
||
# For running it directly (testing purposes) | ||
# if __name__ == "__main__": | ||
# asyncio.run(initialize_db()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,63 @@ | ||
import os | ||
from dotenv import load_dotenv | ||
from pymongo.server_api import ServerApi | ||
from pymongo.mongo_client import MongoClient | ||
""" | ||
Vehicle Allocation System API | ||
This API is designed to manage vehicle allocations for employees. | ||
It includes CRUD operations and history reporting. | ||
""" | ||
|
||
from fastapi import FastAPI | ||
from routers import route | ||
from fastapi.middleware.cors import CORSMiddleware | ||
import uvicorn | ||
|
||
app = FastAPI( | ||
title="Vehicle Allocation System", | ||
description="API for managing vehicle allocations for employees. " | ||
"Includes CRUD operations and history reporting.", | ||
version="1.0.0", | ||
) | ||
|
||
# Include the router from route.py | ||
app.include_router(route.router) | ||
|
||
""" | ||
Set up CORS (for future feat. integration: frontend or external access) | ||
""" | ||
origins = [ | ||
"http://localhost", | ||
"http://localhost:8000", | ||
] | ||
|
||
app.add_middleware( | ||
CORSMiddleware, | ||
allow_origins=origins, | ||
allow_credentials=True, | ||
allow_methods=["*"], | ||
allow_headers=["*"], | ||
) | ||
|
||
# Accessing the root URL | ||
|
||
app = FastAPI() | ||
|
||
@app.get("/") | ||
async def root(): | ||
return {"message": "Welcome to the Vehicle Allocation API. For going to swagger, add '/docs' after http://127.0.0.1:8000/"} | ||
|
||
# Load environment variables from .env file | ||
load_dotenv() | ||
# Health Check endpoint | ||
|
||
# Retrieve the MongoDB credentials from the environment variables | ||
username = os.getenv("MONGO_USERNAME") | ||
password = os.getenv("MONGO_PASSWORD") | ||
cluster = os.getenv("MONGO_CLUSTER_URL") | ||
|
||
# Create the MongoDB connection URI using the loaded credentials | ||
uri = f"mongodb+srv://{username}:{password}@{ | ||
cluster}/?retryWrites=true&w=majority&appName=Cluster0" | ||
@app.get("/health", tags=["Health"]) | ||
async def health_check(): | ||
return {"status": "healthy"} | ||
|
||
|
||
# Create a new client and connect to the server | ||
client = MongoClient(uri, server_api=ServerApi('1')) | ||
# Main entry point when running the app directly | ||
if __name__ == "__main__": | ||
""" | ||
Run the FastAPI application using the uvicorn server. | ||
# Send a ping to confirm a successful connection | ||
try: | ||
client.admin.command('ping') | ||
print("Pinged your deployment. You successfully connected to MongoDB!") | ||
except Exception as e: | ||
print(e) | ||
Host: Binds the server to all available network interfaces. | ||
Port: Runs the server on port 8000. | ||
Reload: Automatically reloads the server when code changes are detected. | ||
""" | ||
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
""" | ||
Pydantic models for the Vehicle Allocation System API. | ||
""" | ||
|
||
from pydantic import BaseModel, Field | ||
from datetime import date | ||
from typing import Optional | ||
|
||
|
||
class Vallocation(BaseModel): | ||
""" | ||
Pydantic model representing a vehicle allocation. | ||
Attributes: | ||
employee_id (int): ID of the employee allocating the vehicle. | ||
vehicle_id (int): ID of the allocated vehicle. | ||
driver_id (int): ID of the driver assigned to the vehicle. | ||
allocation_date (date): The date for which the vehicle is allocated. | ||
status (str, optional): Status of the allocation (e.g., pending, confirmed, canceled). Defaults to "pending". | ||
""" | ||
|
||
employee_id: int = Field(..., | ||
description="ID of the employee allocating the vehicle") | ||
vehicle_id: int = Field(..., description="ID of the allocated vehicle") | ||
driver_id: int = Field(..., | ||
description="ID of the driver assigned to the vehicle") | ||
allocation_date: date = Field(..., | ||
description="The date for which the vehicle is allocated") | ||
status: Optional[str] = Field( | ||
"pending", description="Status of the allocation (e.g., pending, confirmed, cancelled)") | ||
|
||
|
||
class Config: | ||
json_schema_extra = { | ||
"example": { | ||
"employee_id": 123, | ||
"vehicle_id": 456, | ||
"allocation_date": "2024-10-31", | ||
"status": "pending" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,40 @@ | ||
fastapi[all] | ||
pymongo[srv] | ||
# uvicorn | ||
# pymongo[srv] | ||
# pydantic | ||
# python-dotenv | ||
annotated-types==0.7.0 | ||
anyio==4.6.2.post1 | ||
certifi==2024.8.30 | ||
click==8.1.7 | ||
colorama==0.4.6 | ||
dnspython==2.7.0 | ||
email_validator==2.2.0 | ||
fastapi==0.115.3 | ||
fastapi-cli==0.0.5 | ||
h11==0.14.0 | ||
httpcore==1.0.6 | ||
httptools==0.6.4 | ||
httpx==0.27.2 | ||
idna==3.10 | ||
itsdangerous==2.2.0 | ||
Jinja2==3.1.4 | ||
markdown-it-py==3.0.0 | ||
MarkupSafe==3.0.2 | ||
mdurl==0.1.2 | ||
motor==3.6.0 | ||
orjson==3.10.10 | ||
pydantic==2.9.2 | ||
pydantic-extra-types==2.9.0 | ||
pydantic-settings==2.6.0 | ||
pydantic_core==2.23.4 | ||
Pygments==2.18.0 | ||
pymongo==4.9.2 | ||
python-dotenv==1.0.1 | ||
python-multipart==0.0.12 | ||
PyYAML==6.0.2 | ||
rich==13.9.3 | ||
shellingham==1.5.4 | ||
sniffio==1.3.1 | ||
starlette==0.41.0 | ||
typer==0.12.5 | ||
typing_extensions==4.12.2 | ||
ujson==5.10.0 | ||
uvicorn==0.32.0 | ||
watchfiles==0.24.0 | ||
websockets==13.1 |
Oops, something went wrong.