Skip to content

Add FastAPI + MongoDB sample app #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions fastapi-mongo/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
FROM python:3.10-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY main.py .

EXPOSE 8000

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
13 changes: 13 additions & 0 deletions fastapi-mongo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# FastAPI + MongoDB Sample App

This sample demonstrates a simple Student Management API using FastAPI and MongoDB.

## Features

- Create, Read, Update, Delete (CRUD) operations for students
- Async MongoDB access using Motor
- Ready for Keploy API test recording

## Running Locally

1. **Start MongoDB** (Docker example):
Binary file added fastapi-mongo/__pycache__/main.cpython-313.pyc
Binary file not shown.
67 changes: 67 additions & 0 deletions fastapi-mongo/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import List
from motor.motor_asyncio import AsyncIOMotorClient
from bson import ObjectId

app = FastAPI(title="Student Management API (FastAPI + MongoDB)")

# MongoDB connection
MONGO_DETAILS = "mongodb://localhost:27017"
client = AsyncIOMotorClient(MONGO_DETAILS)
db = client.students_db
collection = db.students

class Student(BaseModel):
id: str = Field(default_factory=str, alias="_id")
name: str
age: int

class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}

@app.post("/students", response_model=Student)
async def create_student(student: Student):
student_dict = student.dict(by_alias=True)
student_dict.pop("id", None)
result = await collection.insert_one(student_dict)
student_dict["_id"] = str(result.inserted_id)
return Student(**student_dict)

@app.get("/students", response_model=List[Student])
async def get_students():
students = []
async for doc in collection.find():
doc["_id"] = str(doc["_id"])
students.append(Student(**doc))
return students

@app.get("/students/{student_id}", response_model=Student)
async def get_student(student_id: str):
student = await collection.find_one({"_id": ObjectId(student_id)})
if student:
student["_id"] = str(student["_id"])
return Student(**student)
raise HTTPException(status_code=404, detail="Student not found")

@app.put("/students/{student_id}", response_model=Student)
async def update_student(student_id: str, student: Student):
student_dict = student.dict(by_alias=True)
student_dict.pop("id", None)
result = await collection.update_one(
{"_id": ObjectId(student_id)}, {"$set": student_dict}
)
if result.modified_count == 1:
updated = await collection.find_one({"_id": ObjectId(student_id)})
updated["_id"] = str(updated["_id"])
return Student(**updated)
raise HTTPException(status_code=404, detail="Student not found")

@app.delete("/students/{student_id}")
async def delete_student(student_id: str):
result = await collection.delete_one({"_id": ObjectId(student_id)})
if result.deleted_count == 1:
return {"message": "Student deleted"}
raise HTTPException(status_code=404, detail="Student not found")
4 changes: 4 additions & 0 deletions fastapi-mongo/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
fastapi
uvicorn
motor
pydantic