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:

pip install flask azure-cosmos

Step 2: Set Up Azure Cosmos DB

  1. 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.
  2. 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.

Step 3: Create the Flask Application

  1. Set up the Flask app and establish connection with Cosmos DB.
from flask import Flask, jsonify, request
from azure.cosmos import CosmosClient, exceptions

app = Flask(__name__)

# Azure Cosmos DB connection
url = "YOUR_COSMOS_DB_URI"
key = "YOUR_COSMOS_DB_KEY"
client = CosmosClient(url, credential=key)
database_name = 'flaskDB'
container_name = 'items'
database = client.get_database_client(database_name)
container = database.get_container_client(container_name)

# CRUD Operations

# 1. Create Item
@app.route('/items', methods=['POST'])
def create_item():
    try:
        item = request.get_json()  # Get item data from request
        container.create_item(body=item)  # Insert into Cosmos DB
        return jsonify({"message": "Item created successfully!"}), 201
    except exceptions.CosmosHttpResponseError as e:
        return jsonify({"error": str(e)}), 500

# 2. Read All Items
@app.route('/items', methods=['GET'])
def get_all_items():
    try:
        items = list(container.read_all_items())
        return jsonify(items), 200
    except exceptions.CosmosHttpResponseError as e:
        return jsonify({"error": str(e)}), 500

# 3. Read Item by ID
@app.route('/items/<item_id>', methods=['GET'])
def get_item(item_id):
    try:
        item = container.read_item(item_id, partition_key=item_id)
        return jsonify(item), 200
    except exceptions.CosmosHttpResponseError as e:
        return jsonify({"error": str(e)}), 500

# 4. Update Item by ID
@app.route('/items/<item_id>', methods=['PUT'])
def update_item(item_id):
    try:
        item_data = request.get_json()
        item = container.read_item(item_id, partition_key=item_id)
        item.update(item_data)  # Update item with new data
        container.replace_item(item_id, item)
        return jsonify({"message": "Item updated successfully!"}), 200
    except exceptions.CosmosHttpResponseError as e:
        return jsonify({"error": str(e)}), 500

# 5. Delete Item by ID
@app.route('/items/<item_id>', methods=['DELETE'])
def delete_item(item_id):
    try:
        container.delete_item(item_id, partition_key=item_id)
        return jsonify({"message": "Item deleted successfully!"}), 200
    except exceptions.CosmosHttpResponseError as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)

Step 4: Explanation of CRUD APIs

  1. Create Item: This API accepts a JSON object and inserts it into the Cosmos DB container.
  2. Read All Items: This API fetches all the items stored in the container and returns them in a JSON array.
  3. Read Item by ID: This API retrieves a specific item by its id and returns it.
  4. Update Item by ID: This API updates an existing item based on its id. The PUT request replaces the existing item with new data.
  5. 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:
python app.py

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" }
  • GET /items to get all items:

    • URL: http://127.0.0.1:5000/items
  • GET /items/<item_id> to get an item by its ID:

    • URL: http://127.0.0.1:5000/items/1
  • 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" }
  • DELETE /items/<item_id> to delete an item by its ID:

    • URL: http://127.0.0.1:5000/items/1

Step 7: Handling Errors and Debugging

  • Make sure your Cosmos DB connection strings (URI and KEY) 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.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete