![]() |
Let’s explore a new way to create APIs using FastAPI. It’s fast, easy, and powerful. In this article, we’ll also see how to use MongoDB to do things like adding, reading, updating, and deleting data in our API. MongoDB with FastAPIAfter creating an API, the next step is to have a database that can store the data received through the API, enabling CRUD (Create, Read, Update, Delete) operations. In this article, we will explore MongoDB, a widely-used NoSQL (non-relational) database management system. MongoDB stores data in a flexible, JSON-like format known as BSON (Binary JSON), making it suitable for both structured and semi-structured data. Setting up the ProjectNow, let’s explore a basic example where our primary objective is to perform crud operation in employee details through API endpoints and verify if they are successfully registered in the MongoDB database. MongoDB can be configured either on a local environment (Windows | MacOS) or through the MongoDB Atlas web version. In this article, we will demonstrate the setup with a local MongoDB installation, but the process remains the same for MongoDB Atlas, with the only difference being the connection string. Spinning up MongoDB in MacOS
In this example we would be running the MongoDB as a background process. To run MongoDB the following command can be used mongod --config /usr/local/etc/mongod.conf --fork For MacOS silicon processor use the command mongod --config /opt/homebrew/etc/mongod.conf --fork Output For WindowsOS use the command mongod.exe --config "C:\path\to\your\mongod.conf" The output of the following command would be like in windows about to fork child process, waiting until server is ready for connections. Setup DB and create userTo begin with the furthur steps we need to connect mongosh with the running instance by the command. mongosh Output: First switch to the database that is to be created by the following command. In the following example we will be using the employee database. db = db.getSiblingDB('employee') Output: After creating the database we need to create the user by the following command db.createUser({ Output: After creating the user we can verify if the user creation is successful by following command db.getUsers() The output should be { Output: And with this our MongoDB connection is successful. Connecting MongoDb with Fast APICreating directory and installing dependencies. mkdir fastAPI Output: In the provided code, we create a directory and set up a virtual environment. Establishing a virtual environment is considered a best practice, as it ensures that dependencies are isolated to that specific environment rather than being installed globally. Once the virtual environment is activated, we proceed with the installation of necessary packages using pip. Creating MangoDB ConnectionHere we are creating the MongoDB connection string to connect with the running instance of MongoDB. Python3
In the provided code, we define the data schema that will be stored in the database. This can be regarded as the specific data structure that will encompass the details of employees. Python3
CRUD App with FastAPI and MongoDBCreate Employee: In the create_employee function, we are accepting an employee object of type Employee that we have defined in our schema. As it is a post request we will receive a body where the information of the employee object will be stored. As email is a unique field we first check if the employee with that email exists then we throw a 404 status code else we register the employee to our database. Get All Employee: In the get_all_employees function we get all the employees in our MongoDB. Get Particular Employee: In the get_employee_by_email function, we receive the email from the URL param. After verifying if the email exists in our database we return the employee details. Update Particular Employee: In the update_employee_by_email function, we are receiving a body with updated details. We first check if an employee with the email exists then we check if the email is the same as with the updated details as the email is unique and cannot be changed. After verifying we just update the details of the employee to our database. Delete Particular Employee: In the delete_employee_by_email we are receiving an email for the URL param. So we are verifying whether employees with such emails exist or not. If exist then the details of the employee are deleted from the database. Python3
Testing the APICreate Employee To test the API, create a POST request to the ‘/create_employee/’ endpoint using Postman. We should receive a 200 status code along with the configured success message. The body of the Post request would be { And the returned response should be { Get All Employees To get the list of all employees we need to make a get request in the endpoint ‘/get_all_employees/’. We should receive a 200 status code along with all the employees that are registered in the DB The returned response should be of structure [ Get Particular Employee To get a particular employee we need to pass a param to the url and make a get request to the endpoint ‘/get_employee_by_email/’ so that the information of the particular employee is returned as a response. To perform our testing we can use the following url and the email id is considered a unique attribute in our example. http://localhost:8000/get_employee_by_email/[email protected] And the response returned is { Update Particular Employee in flast api using Mongodb To update a particular employee we need to pass a param to the url so that the information of the particular employee is retrieved and updated with the updated information passed as a body of the post request made in the enpoint ‘/update_employee_by_email/’. To perform our testing we can use the following url and the email id is considered a unique attribute in our example. http://localhost:8000/update_employee_by_email/[email protected] And the body should be passed with the updated information. In the example we are updating the “salary” and “phone_number” attribute. { And the response returned is { Delete Particular Employee To delete a particular employee we need to pass a param to the url and make a delete request to the endpoint ‘/delete_employee_by_email/’ so that the information of the particular employee is deleted from the database. To perform our testing we can use the following url and the email id is considered a unique attribute in our example. http://localhost:8000/delete_employee_by_email/[email protected] And the response returned is { So we have tested all our CRUD endpoints and all the enpoints are working correctly. This ensures that our code implementation is correct. The entire code can be found in the Github Repository. Here is a small video demostration of the above example and setting up the DB connection. In conclusion, we have successfully demonstrated how to set up a FastAPI application to perform CRUD operation, interact with a MongoDB database, and store data. MongoDB’s automatic generation of unique IDs for each request ensures data integrity and easy retrieval. |
Reffered: https://www.geeksforgeeks.org
Python |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |