Build REST CRUD APIs using Azure Cosmos DB and Python Flask
To build a RESTful APIs for CRUD operations with Flask and Azure Cosmos DB, follow these steps:
Prerequisites:
- Azure account: Create an account if you don't already have one Azure Sign Up.
- Azure Cosmos DB: Create a Cosmos DB account (SQL API recommended) from the Azure portal.
- Python environment: Ensure Python 3.7+ is installed.
- Install necessary libraries: Flask and Azure Cosmos DB SDK.
Step 1: Install Required Libraries
You'll need the following libraries for the Flask app and Azure Cosmos DB integration:
Step 2: Set Up Azure Cosmos DB
Create a Cosmos DB account:
- Go to Azure Portal > Create a resource > Azure Cosmos DB.
- Choose
SQL
API. - After the Cosmos DB account is created, get the URI and Primary Key from the
Keys
section of your Cosmos DB instance.
Create a Database and Container:
- In your Cosmos DB instance, create a database (e.g.,
flaskDB
). - Create a container inside the database (e.g.,
items
) with a partition key, such as/id
.
- In your Cosmos DB instance, create a database (e.g.,
Step 3: Create the Flask Application
- Set up the Flask app and establish connection with Cosmos DB.
Step 4: Explanation of CRUD APIs
- Create Item: This API accepts a JSON object and inserts it into the Cosmos DB container.
- Read All Items: This API fetches all the items stored in the container and returns them in a JSON array.
- Read Item by ID: This API retrieves a specific item by its
id
and returns it. - Update Item by ID: This API updates an existing item based on its
id
. ThePUT
request replaces the existing item with new data. - Delete Item by ID: This API deletes an item based on its
id
.
Step 5: Running the Flask App
Once you've written the code:
- Save the script as
app.py
. - Run the app with:
This will start the Flask server on http://127.0.0.1:5000
.
Step 6: Testing the API
You can test your API using tools like Postman or cURL.
POST
/items
to create an item:- URL:
http://127.0.0.1:5000/items
- Body:
{ "id": "1", "name": "item1", "description": "This is item 1" }
- URL:
GET
/items
to get all items:- URL:
http://127.0.0.1:5000/items
- URL:
GET
/items/<item_id>
to get an item by its ID:- URL:
http://127.0.0.1:5000/items/1
- URL:
PUT
/items/<item_id>
to update an item by its ID:- URL:
http://127.0.0.1:5000/items/1
- Body:
{ "name": "updated_item1", "description": "This is the updated item 1" }
- URL:
DELETE
/items/<item_id>
to delete an item by its ID:- URL:
http://127.0.0.1:5000/items/1
- URL:
Step 7: Handling Errors and Debugging
- Make sure your Cosmos DB connection strings (
URI
andKEY
) are correct. - Handle any exceptions such as unauthorized access or network errors by logging or returning error messages.
This basic setup demonstrates how to interact with Azure Cosmos DB from a Flask application and expose CRUD APIs for managing items in the database.