Build an API in less than 30 minutes with ChatGPT and AWS Application Composer — Part 1

Accelerating API Development with Serverless Infrastructure and AI-Powered Code Generation

Ivan Dario Bello Gonzalez
Globant
10 min readApr 11, 2023

--

Created by Midjourney

In modern software development, APIs (Application Programming Interfaces) have become essential for enabling seamless communication and integration between different software applications. APIs provide a standardized and structured way for developers to access the functionality and data of other software systems, whether within their own organization or across different companies and industries. From e-commerce websites to mobile apps to financial services, APIs play a crucial role in enabling efficient and effective software development.

In this two-part article, we will show how to build a simple API using a combination of ChatGPT and AWS Application Composer. In the first part, we will introduce the objective of this document and the prerequisites needed to create the API using AWS Application Composer and explore how to use ChatGPT to write the code for our API. In the second part of the article, we will deploy our API using SAM (AWS Serverless Application Model) and test it with Postman.

Using ChatGPT and AWS Application Composer together, we can build a fully functional API quickly and easily without requiring specialized programming or infrastructure knowledge. So, let’s get started and see how we can use these tools to build an API in less than 30 minutes!

What is ChatGPT?

ChatGPT is a language model trained and developed by OpenAI that can generate human-like responses to natural language inputs. In this tutorial, we will use ChatGPT to write the code for our API, so we won’t need to write any code ourselves. This will allow us to focus on the functionality of the API rather than the implementation details.

What is AWS Application Composer?

On the other hand, AWS Application Composer is a visual builder that simplifies designing, testing, and deploying serverless applications on AWS. With AWS Application Composer, we can create the infrastructure for our API by dragging and connecting AWS services on a visual canvas. This makes it easy to create a serverless API without having to write any IaC (Infrastructure as Code).

Objective

The objective is to create an API using ChatGPT and AWS Application Composer that implements CRUD (Create, Read, Update, and Delete) methods on a randomly generated industry sector. This exercise aims to demonstrate the versatility and power of these tools in building and deploying APIs on the AWS platform: using an API Gateway, Python Lambda functions, and Dynamo DB services. The following diagram shows this architecture:

Architecture diagram for API creation using ChatGPT + AWS Application Compose

Our testing has demonstrated that ChatGPT can generate APIs for any industry, providing users with a powerful and versatile tool for their API development needs. To showcase the flexibility of ChatGPT and AWS Application Composer tools in developing APIs, we used a random industry generator to create our sample API. For this article, we chose to focus on the banking sector as an example.

Result of the random industry generator, we chose to focus on the Banking sector as an example

Prerequisites

Before we get started with building our API, there are a few prerequisites that we need to take care of. These are the prerequisites to be able to perform this demo:

Note: The steps outlined were performed on macOS using the Pycharm IDE and ChatGPT 3.5 standard.

Create a workspace directory

To proceed with this step, first create a workspace directory on your machine named ‘aws_composer_api’. Then, To access AWS Application Composer from the AWS Management Console, navigate to the search bar and type “Application Composer” and select the service from the results, as illustrated in the following image:

The image shows how to access the Application composer service in AWS

To create a new project in AWS Application Composer, click the “Create project” button located at the top right of the interface, then select the “New blank project” option and choose “Connected” from the list of options. We recommend using Chrome or Edge browsers to ensure a seamless file synchronization and real-time review of changes to the AWS CloudFormation template generated by Application Composer. You may need to accept specific browser permissions during setup to enable this feature. Then, click on Create:

The main screen of the options for creating a new project in the AWS Application Composer is displayed.

Create the API architecture in App Composer Canvas

We must set up the necessary resources to begin building our API using AWS Application Composer. Specifically, we must add one API Gateway resource, four Lambda functions, and one DynamoDB table to the project.

This is the AWS Application Composer canvas, and it shows the architecture diagram of the API to be built.

These resources can be easily added to the project canvas by selecting them from the panel on the left-hand side of the AWS Application Composer interface and dragging and dropping them onto the canvas.

The panel on the left of the AWS Application Composer is shown.

Next, select the API Gateway resource on the canvas and add the Routes method by clicking the “Add Route” button in the properties of the API Gateway resource, located in the right pane. Configure four methods — GET, POST, PUT, and DELETE — and click “Save” to complete the setup:

The panel on the right of the API Gateway configuration in the AWS Application Composer is shown.

To properly configure the Lambda resources, you’ll need to modify the functions in the panel on the right. For example, for the “GET” method, you should fill in the panel on the right:

The panel on the right of the Lambda configuration in the AWS Application Composer is shown.

This includes changing the logical ID and source path to match the assigned method and selecting “Python 3.9” as the runtime option. After you’ve made these modifications, do the same for the remaining methods: POST, PUT, and DELETE. It’s worth noting that the other values can be left as default, as shown in the image above. Once you’ve finished configuring your Lambda resources, connect them according to the configured methods.

It is important to note that the permissions and environment variables for Lambda functions are automatically generated based on the established connections. Both AWS Application Composer and AWS Serverless Application Model (SAM) create the necessary policies to execute each function securely. For instance, AWS SAM policy templates such as AWSLambdaBasicExecutionRole allow Lambda functions to write logs, read data from CloudWatch and run with an IAM role.

Create API Python code using ChatGPT

Now we will generate the code for the API using ChatGPT after creating the architecture diagram. The quality of the generated code depends on the dataset used in the tool, and changing the programming language can also impact it. Python was chosen as the programming language for the API, but there are other supported programming languages. Python was chosen as the programming language for the API, but there are other supported programming languages.

We conducted several tests to obtain code with fewer errors, but we found that providing more specific descriptions can further improve the code quality. We encourage readers to experiment with different text inputs to observe the variations in the generated code. For example, adding “handle errors in the function” will prompt ChatGPT to generate “try/except” statements in Python.

The POST method

Below is the text used in the ChatGPT prompt to get the code for the POST method:

Create a python code lambda for a Banking system API. with a POST method that
saves in a dynamo DB(table.put_item). Generate the id item using uuid4 which
the function had to return and invent another 3 items from body related to
Banking, to avoid errors like "Decimal is not JSON serializable" and
"Float types are not supported" add the constructor or library if applicable.
The name of the handler function is def handler(event, context). The Dynamo
table is an environment variable os.environ['TABLE_NAME']. The architecture
is AWS API gateway, a lambda function, and Dynamo DB.

Now, let’s review this prompt in detail. In the first part, we specify that we want to generate Python API code for a specific industry sector using AWS Lambda. We then request a POST method and use the Boto3 library. Next, we instruct ChatGPT to create the first attribute, named “id” because it’s the default partition key generated by AWS Application Composer. Lastly, we request that ChatGPT create additional item attributes related to the chosen sector. ChatGPT generates different attributes for each test, depending on the specified sector.

We then tell ChatGPT to avoid serialization errors if applicable, as we discovered these errors during our initial tests. In the following part, we use the default values configured by AWS Application Composer, such as the environment variable for the Dynamo table and function names. Finally, we provide information about the API’s architecture to clarify our requirements.

This is the output generated by ChatGPT for the POST method:

The GET Method

To create the GET method, we began by making adjustments to the prompt wording, specifically asking ChatGPT to generate a function for the GET method that retrieves items from the DynamoDB table. We then incorporated the table.query method into the generated code.

Finally, we added specific details about the items we wanted to retrieve to provide ChatGPT with a better understanding of our desired outcome. This iterative process resulted in codes tailored to our specific needs and increased the overall quality of the application. This is the text of the ChatGPT prompt:

Create a python code lambda for a Banking system API.
with a GET method that retrieves in a dynamo DB (table.query), which retrieves
an item based on the sent id in the event['queryStringParameters']['id'], to
avoid errors like "Decimal is not JSON serializable" and "Float types are not
supported" add the constructor or library if applicable.
The name of the handler function is def handler(event, context). The Dynamo
table is an environment variable os.environ['TABLE_NAME'].
The architecture is AWS API gateway, a lambda function, and Dynamo DB.
These are the 5 item to retrieve:
item = {
'id': id,
'name': body['name'],
'balance': Decimal(str(body['balance'])),
'account_type': body['account_type'],
'interest_rate': Decimal(str(body['interest_rate']))
}

This is the output generated by ChatGPT is the resulting code for the GET method:

The PUT Method

In the same manner as the GET method, we modified the wording to instruct ChatGPT to generate a function for the PUT method, specifying the use of the “‘queryStringParameters’” for updating an item and providing the list of items to be used as a reference. This is the text of the r ChatGPT prompt:

Create a python code lambda for a Banking system API.
with a PUT method that updates in a dynamo DB (table.update_item), which
updates an item based on the sent id in the
event['queryStringParameters']['id'], to avoid errors like
"Decimal is not JSON serializable" and "Float types are not supported"
add the constructor or library if applicable.
The name of the handler function is def handler(event, context). The Dynamo
table is an environment variable os.environ['TABLE_NAME'].
The architecture is AWS API gateway, a lambda function, and Dynamo DB.
these are the 5 item to update:
item = {
'id': id,
'name': body['name'],
'balance': Decimal(str(body['balance'])),
'account_type': body['account_type'],
'interest_rate': Decimal(str(body['interest_rate']))
}

This is the output generated by ChatGPT for the PUT method:

The DELETE Method

We only changed a few verbs for the DELETE method to convey the intended action of deleting an item. Therefore, we have not added any items at the end of the text. At this point, we can omit the part of the text that instructs ChatGPT to handle serialized errors. Interestingly, we observed that including this text resulted in the inclusion of libraries that were not used. This is the text for the ChatGPT prompt:

Create a python code lambda for a Banking system API.
with a DELETE method that deletes in a dynamo DB (table.delete_item), which
deletes an item based on the sent id in the
event['queryStringParameters']['id'], to avoid errors like "Decimal is not
JSON serializable" and "Float types are not supported" add the constructor or
library if applicable.
The name of the handler function is def handler(event, context). The Dynamo
table is an environment variable os.environ['TABLE_NAME']. The function should
return message deleted successfully
The architecture is AWS API gateway, a lambda function, and Dynamo DB.

This is the output generated by ChatGPT for the DELETE method:

After generating the code for our API, the next step is to deploy it using AWS SAM, which will be discussed in the following article, part 2.

Conclusions

AWS Application Composer offers several benefits for developers and organizations seeking to streamline application deployment. By creating applications quickly, this tool reduces the need for additional steps and simplifies the overall development process. One key advantage is that, based on the connections made in the canvas, AWS Application Composer automatically generates permissions, variables, and logic according to the resources used. As a result, developers can create a repository of files that can be easily shared among team members.

Meanwhile, using ChatGPT to generate the code provided an added layer of value, allowing us to focus on improving the code quality and security, handling errors, and implementing authentication. Although ChatGPT occasionally generates incorrect code, it still comes very close to the desired requirements in the architecture diagram.

In the second part of this article, we will deploy this API using SAM (AWS Serverless Application Model) and test it with Postman.

References

--

--

Ivan Dario Bello Gonzalez
Globant

Cloud Engineer, Sr | AWS x 3 | GCP x 1 | HashiCorp x 1 | Master's student in Information and Communication Sciences - last semester.