DEV Community

Cover image for Rapid API Creation with AWS Amplify
K for Fullstack Frontend

Posted on

Rapid API Creation with AWS Amplify

For a long time, frontend devs were forced to get the help of a backend dev to get an API up and running for their web app. It's like the cloud's story, where you had to order servers and wait weeks, and then you had to pay someone to maintain them. The cloud changed that it enabled people to rent VMs in a data center with a few second's notice.

The creation of APIs got quicker in the last years too. Offerings like managed API-gateways functions as a service (FaaS), and backends as a service (BaaS) made it a breeze. Just sign up to a cloud provider, upload your function code, and be ready to go.

One tool to help us frontend devs here is AWS Amplify. AWS attempts to make all its services, especially the managed/serverless ones, more comfortable to use for frontend devs. Amplify wants to be the Ruby on Rails of the serverless age.

In this article, I'll show you how fast you can get a REST, and GraphQL API set up with authentication with just a few commands.

Prerequisites

You will need an AWS Account, Node.js, NPM, the AWS CLI.

I will use the AWS Cloud9 IDE because it comes preinstalled with these tools.

Install the Amplify CLI

The Amplify CLI can be installed with NPM.

$ npm install -g @aws-amplify/cli
Enter fullscreen mode Exit fullscreen mode

Cloud9 has a local AWS profile managed by the IDE, so we don't have to manage it. The only problem is, it comes with a file name the Amplify CLI doesn't recognize. This means we have to create a symlink for it.

$ ln -s ~/.aws/credentials ~/.aws/config
Enter fullscreen mode Exit fullscreen mode

After that, we can run the configuration with the following command:

$ amplify configure
Enter fullscreen mode Exit fullscreen mode

Creating a Project

To create a new project, we can use NPM in turn with the Amplify CLI:

$ mkdir amplify-apis
$ cd amplify-apis
$ npm init
$ amplify init
Enter fullscreen mode Exit fullscreen mode

We can use all the defaults here.

Adding a REST API

The first API we are going to add is a REST API. For this, we have to run the following command:

$ amplify add api
Enter fullscreen mode Exit fullscreen mode

This will be a REST API, so we have to choose REST initially; after that, we can use almost all the defaults. The only thing we don't want to do is to restrict the API access: ? Restrict API access No.

This API's endpoint will be backed by an API-Gateway and an AWS Lambda function. The function code can be found in

amplify-apis/amplify/backend/function/amplifyapis<some_id>/src/index.js
Enter fullscreen mode Exit fullscreen mode

We have to add a CORS header to the response in the Lambda function code to test it.

exports.handler = async () => ({
  headers: { "Access-Control-Allow-Origin": "*"},
  statusCode: 200,
  body: JSON.stringify("Hello from Lambda!"),
});
Enter fullscreen mode Exit fullscreen mode

Deploying the REST API

To deploy the newly added REST API, we have to run the following command:

$ amplify push
Enter fullscreen mode Exit fullscreen mode

This will ask us if we want to update the resources in the cloud. It also shows us again that we have an Api and a Function resource defined.

After a few seconds, we get the URL where the API was deployed to.

Using the REST API

If we want to use the REST API by merely copying the URL from the CLI in a browser, we get an authentication error. To use it, we have to set the right credentials. The easiest way is to use the API client of the Amplify JS SDK.

The Amplify CLI has created an aws-exports.js file with the credentials inside our src directory, so we can create an index.html file inside that directory too, to use the credentials.

The index.html should contain the following code:

<!doctype html>
<script src="https://unpkg.com/aws-amplify@3.0.22/dist/aws-amplify.min.js"></script>
<script type="module">
import credentials from "./aws-exports.js";
const { Amplify, API } = window.aws_amplify;
Amplify.configure(credentials);
API.get("<API_NAME>", "/items").then(r => alert(r));
</script>
Enter fullscreen mode Exit fullscreen mode

Replace the <API_NAME> placeholder with the name from the aws-exports.js file.

If we preview the HTML file, we should get an alert pop-up with "Hello from Lambda!".

Adding a GraphQL API

Next, we add a GraphQL API; for this, we can use the same command as before:

$ amplify add api
Enter fullscreen mode Exit fullscreen mode

This time, of course, we have to choose "GraphQL" as our API type. After that, we can use all the defaults.

The GraphQL schema can be found at:

amplify-apis/amplify/backend/api/amplifyapis/schema.graphql
Enter fullscreen mode Exit fullscreen mode

And it looks like this:

type Todo @model {
  id: ID!
  name: String!
  description: String
}
Enter fullscreen mode Exit fullscreen mode

The @model directive will lead to the automatic creation of DynamoDB tables for the type when we deploy the API.

Deploying the GraphQL API

To deploy, we rerun the push command.

$ amplify push
Enter fullscreen mode Exit fullscreen mode

This will show us that new Api resources will be created when we confirm.

After that, the CLI also asks some questions about code generation for the GraphQL queries; we can use the defaults here.

After a few minutes, we will be presented with an URL for the freshly created GraphQL API again.

Again, all the credentials end up inside the src/aws-exports.js file, so we don't have to change the config in our HTML file.

Amplify also has generated JavaScript code for us inside src/graphql, so we don't have to write GraphQL queries manually.

Using the GraphQL API

To use the GraphQL API, we have to change some code in our src/index.html file:

<!doctype html>
<title>Amplify APIs</title>
<script src="https://unpkg.com/aws-amplify@3.0.22/dist/aws-amplify.min.js"></script>
<script type="module">
import credentials from "./aws-exports.js";
import * as queries from "./graphql/queries.js";
const { Amplify, API, graphqlOperation } = window.aws_amplify;
Amplify.configure(credentials);
Promise.all([
  API.get("<API_NAME>", "/items"),
  API.graphql(graphqlOperation(queries.listTodos)),
]).then(([rest, graphql]) => {
  alert(rest);
  alert(JSON.stringify(graphql));
});
</script>
Enter fullscreen mode Exit fullscreen mode

We can use the generated src/graphql/queries.js file, so we don't have to write queries.

The get and graphql methods of API return a promise, we will wait for all of them to resolve and then show alerts with the result.

The REST API only returns a string so that we can display it immediately, but the GraphQL API returns JSON that is parsed to an object for use by the client, so we have to convert it to a string again before alerting.

Conclusion

Only a handful of CLI commands are required to create two APIs from scratch. There was a credential file created that we can share with our co-workers so they can access the APIs right away. The GraphQL API even came with some basic queries generated for us.

All these commands have more config options, and even come with more complex API templates we can use as a starting point.

Everything uses well known AWS services and results in CloudFormation templates you can edit on your own if needed.

Top comments (0)