From 8e0ca1606df763a1d125f61a900b98cf0ae19f6f Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh <148898879+rachel-mack@users.noreply.github.com> Date: Mon, 16 Jun 2025 16:43:06 -0400 Subject: [PATCH 1/2] Move to pymongo async (#1) * Update app.py * Update requirements.txt * Update requirements.in * remove dev-req files * update pymongo version --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 2507499..56e7967 100644 --- a/requirements.txt +++ b/requirements.txt @@ -30,7 +30,7 @@ pydantic==2.6.3 # fastapi pydantic-core==2.16.3 # via pydantic -pymongo==4.5.0 +pymongo==4.13.1 # via motor sniffio==1.3.0 # via anyio From 4995fbfeac1d5011a1d86ce4904d335599226898 Mon Sep 17 00:00:00 2001 From: Rachel Mackintosh Date: Tue, 15 Jul 2025 11:37:51 -0400 Subject: [PATCH 2/2] pymongo and create_student --- app.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/app.py b/app.py index 67fbfa2..14850d6 100644 --- a/app.py +++ b/app.py @@ -9,16 +9,17 @@ from typing_extensions import Annotated from bson import ObjectId -import asyncio +import pymongo from pymongo import AsyncMongoClient from pymongo import ReturnDocument +from pymongo.server_api import ServerApi app = FastAPI( title="Student Course API", summary="A sample application showing how to use FastAPI to add a ReST API to a MongoDB collection.", ) -client = AsyncMongoClient(os.environ["MONGODB_URL"]) +client = AsyncMongoClient(os.environ["MONGODB_URL"],server_api=pymongo.server_api.ServerApi(version="1", strict=True,deprecation_errors=True)) db = client.college student_collection = db.get_collection("students") @@ -100,13 +101,11 @@ async def create_student(student: StudentModel = Body(...)): A unique `id` will be created and provided in the response. """ - new_student = await student_collection.insert_one( - student.model_dump(by_alias=True, exclude=["id"]) - ) - created_student = await student_collection.find_one( - {"_id": new_student.inserted_id} - ) - return created_student + new_student = student.model_dump(by_alias=True, exclude=["id"]) + result = await student_collection.insert_one(new_student) + new_student["_id"] = result.inserted_id + + return new_student @app.get(