DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Low Code Approach for Building a Serverless REST API
  • How to Configure AWS Glue Job Using Python-Based AWS CDK
  • Building a Scalable ML Pipeline and API in AWS
  • AWS Cloud Security: Key Components, Common Vulnerabilities, and Best Practices

Trending

  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • Docker Model Runner: Streamlining AI Deployment for Developers
  • A Guide to Developing Large Language Models Part 1: Pretraining
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Building a REST API With AWS Gateway and Python

Building a REST API With AWS Gateway and Python

Build a REST API using AWS Gateway and Python with our easy tutorial. Build secure and robust APIs that developers will love to build applications for.

By 
Derric Gilling user avatar
Derric Gilling
DZone Core CORE ·
Mar. 29, 23 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
5.5K Views

Join the DZone community and get the full member experience.

Join For Free

AWS Gateway is a powerful tool for building APIs that scale to meet the demands of modern web and mobile applications. With AWS Gateway, you can create RESTful APIs that expose your data and business logic to developers who can then build rich, interactive applications that consume your API.

REST API is an industry standard for building scalable, distributed web applications. With AWS Gateway, you can easily build a REST API that supports both GET and POST methods, as well as complex query parameters. You can also add support for other HTTP methods, such as PUT, DELETE, and HEAD.

Using AWS Gateway, you can quickly create APIs that are secure and robust. You can also use it to deploy your code to a production environment with minimal effort. Additionally, AWS Gateway allows for seamless integration with other AWS services, such as S3 and DynamoDB, enabling you to easily add complex functionality to your APIs.

Pre-requisites

Before building a RESTful API with AWS Gateway, you should have the following in place:

  • Create an AWS account if you don’t have one already.
  • Log in to the AWS Management Console and navigate to the Amazon API Gateway service.

AWS Gateway


  • Click on "Create API" and select "REST API".


REST API


Choose the protocol


New child resource

  • Click on "Actions" to define the resource and click "Create Method".

Actions


GET - Setup

  • Choose the HTTP verb (e.g. GET, POST, PUT, etc.) and click on the checkmark to create the method.

  • In the "Integration type" section, select "Lambda Function" and enter the name of the Lambda function you want to use to handle the API requests.

  • Click on "Save" to create the API.

AWS Lambda


  • Select Node from the Runtime Dropdown.

Create function


Code Example

Python
 

import json
# Example data

data = {
    "items": [
        {"id": 1, "name": "Item 1", "price": 10.99},
        {"id": 2, "name": "Item 2", "price": 15.99},
        {"id": 3, "name": "Item 3", "price": 20.99},
    ]
}

def lambda_handler(event, context):
    # Determine the HTTP method of the request
    http_method = event["httpMethod"]
    # Handle GET request
    if http_method == "GET":
        # Return the data in the response
        response = {
            "statusCode": 200,
            "body": json.dumps(data)
        }
        return response

    # Handle POST request
    elif http_method == "POST":
        # Retrieve the request's body and parse it as JSON
        body = json.loads(event["body"])
        # Add the received data to the example data
        data["items"].append(body)
        # Return the updated data in the response
        response = {
            "statusCode": 200,
            "body": json.dumps(data)
        }
        return response

    # Handle PUT request
    elif http_method == "PUT":
        # Retrieve the request's body and parse it as JSON
        body = json.loads(event["body"])
        # Update the example data with the received data
        for item in data["items"]:
            if item["id"] == body["id"]:
                item.update(body)
                break
        # Return the updated data in the response
        response = {
            "statusCode": 200,
            "body": json.dumps(data)
        }
        return response

         # Handle DELETE request
    elif http_method == "DELETE":
        # Retrieve the request's body and parse it as JSON
        body = json.loads(event["body"])
        # Find the item with the specified id in the example data
        for i, item in enumerate(data["items"]):
            if item["id"] == body["id"]:
                # Remove the item from the example data
                del data["items"][i]
                break
        # Return the updated data in the response
        response = {
            "statusCode": 200,
            "body": json.dumps(data)
        }
        return response

    else:
        # Return an error message for unsupported methods
        response = {
            "statusCode": 405,
            "body": json.dumps({"error": "Method not allowed"})
        }
        return response


This code defines a Lambda function, lambda_handler, that handles different types of HTTP requests (GET, POST, PUT, DELETE) on some data. The data is an object containing an array of items, each item has an id, name, and price.

When the function is called, it first determines the HTTP method of the request from the event object. Then it handles the request accordingly:

  • GET: returns the data in the response with a status code of 200.
  • POST: retrieves the request's body and parses it as JSON, then add the received data to the example data, then returns the updated data in the response with a status code of 200.
  • PUT: retrieves the request's body and parses it as JSON, then updates the example data with the received data, then returns the updated data in the response with a status code of 200.
  • DELETE: retrieves the request's body and parses it as JSON, then find the item with the specified id in the example data and removes it, then returns the updated data in the response with a status code of 200.
  • If the method is not supported, it will return an error message with a status code of 405.

Deploy the API by clicking on "Actions" and selecting "Deploy API".

Deploy the API


Select a deployment stage (e.g. "prod" or "test") and click on "Deploy".
Use the generated API endpoint to make requests to your API.

Deploy API


Running and Testing the Code in Postman

Now, our API is up and running. You can send a test HTTP request through Postman. By sending a request to your invoke URL, you should see a 200 OK status code. For this test, no request body is needed for the incoming request.


postman


API AWS REST AWS Lambda Cloud AWS Cloud

Published at DZone with permission of Derric Gilling. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Low Code Approach for Building a Serverless REST API
  • How to Configure AWS Glue Job Using Python-Based AWS CDK
  • Building a Scalable ML Pipeline and API in AWS
  • AWS Cloud Security: Key Components, Common Vulnerabilities, and Best Practices

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!