Connect to an external HTTP endpoint
The HTTP Datasource allows you to quickly configure HTTP resolvers within your Data API.
This guide will demonstrate how to establish a connection to an external REST API using an HTTP data source and use Amplify Data's custom mutations and queries to interact with the REST API.
Step 1 - Set up your custom type
For the purpose of this guide we will define a Post type and use an existing external REST API that will store records for it. In Amplify Gen 2, customType adds a type to the schema that is not backed by an Amplify-generated DynamoDB table.
With the Post type defined, it can then be referenced as the return type when defining your custom queries and mutations.
First, add the Post custom type to your schema:
import { type ClientSchema, a, defineData } from "@aws-amplify/backend";
const schema = a.schema({ Todo: a .model({ content: a.string(), }) .authorization(allow => [allow.publicApiKey()]), Post: a.customType({ title: a.string(), content: a.string(), author: a.string().required(), }),});
export type Schema = ClientSchema<typeof schema>;
export const data = defineData({ schema, authorizationModes: { defaultAuthorizationMode: 'apiKey', apiKeyAuthorizationMode: { expiresInDays: 30, }, },});Step 2 - Add your REST API or HTTP API as Datasource
To integrate the external REST API or HTTP API, you'll need to set it up as the HTTP Datasource. Add the following code in your amplify/backend.ts file.
import { defineBackend } from "@aws-amplify/backend";import { auth } from "./auth/resource";import { data } from "./data/resource";
const backend = defineBackend({ auth, data,});
const httpDataSource = backend.data.addHttpDataSource( "HttpDataSource", "https://www.example.com");Step 3 - Define custom queries and mutations
Now that your REST API has been added as a data source, you can reference it in custom queries and mutations using the a.handler.custom() modifier which accepts the name of the data source and an entry point for your resolvers.
Use the following code examples to add addPost, getPost, updatePost, and deletePost as custom queries and mutations to your schema:
import { type ClientSchema, a, defineData } from "@aws-amplify/backend";
const schema = a.schema({ Post: a.customType({ title: a.string(), content: a.string(), author: a.string().required(), }), addPost: a .mutation() .arguments({ title: a.string(), content: a.string(), author: a.string().required(), }) .returns(a.ref("Post")) .authorization(allow => [allow.publicApiKey()]) .handler( a.handler.custom({ dataSource: "HttpDataSource", entry: "./addPost.js", }) ),});
export type Schema = ClientSchema<typeof schema>;
export const data = defineData({ schema, authorizationModes: { defaultAuthorizationMode: 'apiKey', apiKeyAuthorizationMode: { expiresInDays: 30, }, },});import { type ClientSchema, a, defineData } from "@aws-amplify/backend";
const schema = a.schema({ Post: a.customType({ title: a.string(), content: a.string(), author: a.string().required(), }), getPost: a .query() .arguments({ id: a.id().required() }) .returns(a.ref("Post")) .authorization(allow => [allow.publicApiKey()]) .handler( a.handler.custom({ dataSource: "HttpDataSource", entry: "./getPost.js", }) ),});
export type Schema = ClientSchema<typeof schema>;
export const data = defineData({ schema, authorizationModes: { defaultAuthorizationMode: 'apiKey', apiKeyAuthorizationMode: { expiresInDays: 30, }, },});import { type ClientSchema, a, defineData } from "@aws-amplify/backend";
const schema = a.schema({ Post: a.customType({ title: a.string(), content: a.string(), author: a.string().required(), }), updatePost: a .mutation() .arguments({ id: a.id().required(), title: a.string(), content: a.string(), author: a.string(), }) .returns(a.ref("Post")) .authorization(allow => [allow.publicApiKey()]) .handler( a.handler.custom({ dataSource: "HttpDataSource", entry: "./updatePost.js", }) ),});
export type Schema = ClientSchema<typeof schema>;
export const data = defineData({ schema, authorizationModes: { defaultAuthorizationMode: 'apiKey', apiKeyAuthorizationMode: { expiresInDays: 30, }, },});import { type ClientSchema, a, defineData } from "@aws-amplify/backend";
const schema = a.schema({ Post: a.customType({ title: a.string(), content: a.string(), author: a.string().required(), }), deletePost: a .mutation() .arguments({ id: a.id().required() }) .returns(a.ref("Post")) .authorization(allow => [allow.publicApiKey()]) .handler( a.handler.custom({ dataSource: "HttpDataSource", entry: "./deletePost.js", }) ),});
export type Schema = ClientSchema<typeof schema>;
export const data = defineData({ schema, authorizationModes: { defaultAuthorizationMode: 'apiKey', apiKeyAuthorizationMode: { expiresInDays: 30, }, },});Step 4 - Configure custom business logic handler code
Next, create the following files in your amplify/data folder and use the code examples to define custom resolvers for the custom queries and mutations added to your schema from the previous step. These are AppSync JavaScript resolvers.
import { util } from "@aws-appsync/utils";
export function request(ctx) { return { method: "POST", resourcePath: "/post", params: { headers: { "Content-Type": "application/json", }, body: { title: ctx.arguments.title, content: ctx.arguments.content, author: ctx.arguments.author, }, }, };}
export function response(ctx) { if (ctx.error) { return util.error(ctx.error.message, ctx.error.type); } if (ctx.result.statusCode == 200) { return JSON.parse(ctx.result.body).data; } else { return util.appendError(ctx.result.body, "ctx.result.statusCode"); }}import { util } from "@aws-appsync/utils";
export function request(ctx) { return { method: "GET", resourcePath: "/posts/" + ctx.arguments.id, params: { headers: { "Content-Type": "application/json", }, }, };}
export function response(ctx) { if (ctx.error) { return util.error(ctx.error.message, ctx.error.type); } if (ctx.result.statusCode == 200) { return JSON.parse(ctx.result.body).data; } else { return util.appendError(ctx.result.body, "ctx.result.statusCode"); }}import { util } from "@aws-appsync/utils";
export function request(ctx) { return { method: "POST", resourcePath: "/posts/" + ctx.arguments.id, params: { headers: { "Content-Type": "application/json", }, body: { title: ctx.arguments.title, content: ctx.arguments.content, author: ctx.arguments.author, }, }, };}
export function response(ctx) { if (ctx.error) { return util.error(ctx.error.message, ctx.error.type); } if (ctx.result.statusCode == 200) { return JSON.parse(ctx.result.body).data; } else { return util.appendError(ctx.result.body, "ctx.result.statusCode"); }}import { util } from "@aws-appsync/utils";
export function request(ctx) { return { method: "DELETE", resourcePath: "/posts/" + ctx.arguments.id, params: { headers: { "Content-Type": "application/json", }, }, };}
export function response(ctx) { if (ctx.error) { return util.error(ctx.error.message, ctx.error.type); } if (ctx.result.statusCode == 200) { return JSON.parse(ctx.result.body).data; } else { return util.appendError(ctx.result.body, "ctx.result.statusCode"); }}Step 5 - Invoke custom queries or mutations
From your client code, you can create a custom GraphQL request for each custom query and mutation. First define a data class that matches the Post return type:
data class Post( val title: String?, val content: String?, val author: String)data class AddPostResponse( val addPost: Post)
val document = """ mutation AddPost(${'$'}title: String, ${'$'}content: String, ${'$'}author: String!) { addPost(title: ${'$'}title, content: ${'$'}content, author: ${'$'}author) { title content author } }""".trimIndent()
val request = SimpleGraphQLRequest<String>( document, mapOf( "title" to "My Post", "content" to "My Content", "author" to "Chris" ), String::class.java, GsonVariablesSerializer())
Amplify.API.mutate( request, { if (it.hasErrors()) { Log.e("MyAmplifyApp", "Mutation returned errors: ${it.errors}") } else { var gson = Gson() val response = gson.fromJson(it.data, AddPostResponse::class.java) Log.i("MyAmplifyApp", "${response.addPost}") } }, { Log.e("MyAmplifyApp", "Mutation failed", it) })data class GetPostResponse( val getPost: Post)
val document = """ query GetPost(${'$'}id: ID!) { getPost(id: ${'$'}id) { title content author } }""".trimIndent()
val request = SimpleGraphQLRequest<String>( document, mapOf( "id" to "<post-id>" ), String::class.java, GsonVariablesSerializer())
Amplify.API.query( request, { if (it.hasErrors()) { Log.e("MyAmplifyApp", "Query returned errors: ${it.errors}") } else { var gson = Gson() val response = gson.fromJson(it.data, GetPostResponse::class.java) Log.i("MyAmplifyApp", "${response.getPost}") } }, { Log.e("MyAmplifyApp", "Query failed", it) })data class UpdatePostResponse( val updatePost: Post)
val document = """ mutation UpdatePost(${'$'}id: ID!, ${'$'}title: String) { updatePost(id: ${'$'}id, title: ${'$'}title) { title content author } }""".trimIndent()
val request = SimpleGraphQLRequest<String>( document, mapOf( "id" to "<post-id>", "title" to "An Updated Post" ), String::class.java, GsonVariablesSerializer())
Amplify.API.mutate( request, { if (it.hasErrors()) { Log.e("MyAmplifyApp", "Mutation returned errors: ${it.errors}") } else { var gson = Gson() val response = gson.fromJson(it.data, UpdatePostResponse::class.java) Log.i("MyAmplifyApp", "${response.updatePost}") } }, { Log.e("MyAmplifyApp", "Mutation failed", it) })data class DeletePostResponse( val deletePost: Post)
val document = """ mutation DeletePost(${'$'}id: ID!) { deletePost(id: ${'$'}id) { title content author } }""".trimIndent()
val request = SimpleGraphQLRequest<String>( document, mapOf( "id" to "<post-id>" ), String::class.java, GsonVariablesSerializer())
Amplify.API.mutate( request, { if (it.hasErrors()) { Log.e("MyAmplifyApp", "Mutation returned errors: ${it.errors}") } else { var gson = Gson() val response = gson.fromJson(it.data, DeletePostResponse::class.java) Log.i("MyAmplifyApp", "${response.deletePost}") } }, { Log.e("MyAmplifyApp", "Mutation failed", it) })Conclusion
In this guide, you’ve added an external REST API as a HTTP data source to an Amplify Data API and defined custom queries and mutations, handled by AppSync JS resolvers, to manipulate Post items in an external REST API using the Amplify Gen 2 Data client.
To clean up, you can delete your sandbox by accepting the prompt when terminating the sandbox process in your terminal. Alternatively, you can also use the AWS Amplify console to manage and delete sandbox environments.