8 Best Practices for Building FastAPI and MongoDB Applications

8 Best Practices for Building FastAPI and MongoDB Applications

Originally Published Apr 23, 2024

FastAPI seamlessly integrates with MongoDB through the Motor library, enabling asynchronous database interactions.

Read more on Developer Center

Author: Mark Smith

1 Like

I’m commenting only to point out that the link to github doesn’t seem to work

1 Like

@Alessio_Ruggi Thanks for the heads-up! I’ve just fixed it.

4 Likes

Hello @DeveloperCenter,

I followed these steps and the APIs were working fine until few months ago. Also, I have not used Motor and gone with pymongo[srv]. The mongo db is starting to throw connection timeout error intermittently. Following is my setup code:

def db_lifespan(app: FastAPI):
# Startup
server_api = ServerApi(ā€˜1’)
app.mongodb_client = MongoClient(CONNECTION_STRING,
maxIdleTimeMS=600000,
maxConnecting=5,
timeoutMS=90000,
socketTimeoutMS=90000,
serverMonitoringMode=ā€œpollā€,
server_api=server_api)
app.database = app.mongodb_client.get_database(DB_NAME)
ping_response = app.database.command(ā€œpingā€)
if int(ping_response[ā€œokā€]) != 1:
raise Exception(ā€œProblem connecting to database cluster.ā€)
else:
logger.info(ā€œConnected to database cluster.ā€)

yield

# Shutdown
app.mongodb_client.close() 

Could anyone please help me out with the issue?

3 Likes

I’m facing the same issue currently did you figure out the actual issue and a fix.