Python Flask + AWS DynamoDB: Full CRUD API with Postman Testing


This guide walks you through setting up AWS DynamoDB, creating a Flask API with CRUD operations, and testing it with Postman.


1. Configuring AWS Credentials

Before interacting with DynamoDB, configure AWS credentials.

Step 1: Generate AWS Access & Secret Keys

  1. Sign in to AWS Console
  2. Go to IAMUsers → Select User → Security credentials
  3. Create and copy the Access Key ID & Secret Access Key

Step 2: Configure AWS CLI

Run the following command in your terminal:

aws configure

Enter:

AWS Access Key ID: YOUR_ACCESS_KEY
AWS Secret Access Key: YOUR_SECRET_KEY
Default region name: us-east-1
Default output format: json

2. Creating a DynamoDB Table

Before building our Flask app, we need a DynamoDB table.

Step 1: Install Boto3 (AWS SDK for Python)

pip install boto3

Step 2: Create a Python Script create_table.py

import boto3

dynamodb = boto3.client('dynamodb')

table_name = "Users"

dynamodb.create_table(
    TableName=table_name,
    KeySchema=[{'AttributeName': 'user_id', 'KeyType': 'HASH'}],
    AttributeDefinitions=[{'AttributeName': 'user_id', 'AttributeType': 'S'}],
    ProvisionedThroughput={'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5}
)

print(f"Table {table_name} created successfully!")

Step 3: Run the Script to Create the Table

python create_table.py

3. Setting Up Flask Project

Step 1: Create and Activate a Virtual Environment

mkdir flask-dynamodb-app && cd flask-dynamodb-app
python3 -m venv venv
source venv/bin/activate  # On Windows, use `venv\Scripts\activate`

Step 2: Install Required Packages

pip install flask boto3 flask-restful

4. Creating Flask App with CRUD Operations

Create a file named app.py and add the following code:

from flask import Flask, request, jsonify
import boto3
import uuid

app = Flask(__name__)

# Initialize DynamoDB resource
dynamodb = boto3.resource('dynamodb')
table_name = "Users"

# Get the DynamoDB table
def get_table():
    return dynamodb.Table(table_name)

# Home Route
@app.route('/')
def home():
    return jsonify({"message": "Flask + AWS DynamoDB API is running!"})

# Create User
@app.route('/users', methods=['POST'])
def create_user():
    data = request.json
    user_id = str(uuid.uuid4())  # Generate unique user ID
    get_table().put_item(Item={"user_id": user_id, "name": data["name"]})
    return jsonify({"message": "User added", "user_id": user_id})

# Get User
@app.route('/users/<user_id>', methods=['GET'])
def get_user(user_id):
    response = get_table().get_item(Key={"user_id": user_id})
    return jsonify(response.get("Item", {"error": "User not found"}))

# Update User
@app.route('/users/<user_id>', methods=['PUT'])
def update_user(user_id):
    data = request.json
    get_table().update_item(
        Key={"user_id": user_id},
        UpdateExpression="SET #nm = :val1",
        ExpressionAttributeNames={"#nm": "name"},
        ExpressionAttributeValues={":val1": data["name"]}
    )
    return jsonify({"message": "User updated"})

# Delete User
@app.route('/users/<user_id>', methods=['DELETE'])
def delete_user(user_id):
    get_table().delete_item(Key={"user_id": user_id})
    return jsonify({"message": "User deleted"})

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

Step 3: Run the Flask App

python app.py

Check if the API is running: http://127.0.0.1:5000/


5. Testing with Postman

Step 1: Install Postman

Download Postman if not installed.

Step 2: Perform API Requests

Create User (POST)

  • URL: http://127.0.0.1:5000/users
  • Body (JSON):
    { "name": "John Doe" }
  • Response:
    { "message": "User added", "user_id": "1234-uuid" }

Get User (GET)

  • URL: http://127.0.0.1:5000/users/{user_id}
  • Response (if found):
    { "user_id": "1234-uuid", "name": "John Doe" }

Update User (PUT)

  • URL: http://127.0.0.1:5000/users/{user_id}
  • Body (JSON):
    { "name": "Updated John" }
  • Response:
    { "message": "User updated" }

Delete User (DELETE)

  • URL: http://127.0.0.1:5000/users/{user_id}
  • Response:
    { "message": "User deleted" }

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