Introducing the AWS Amplify GraphQL Client

A first look at how to build client side GraphQL applications using AWS Amplify.

Setup

npm i aws-amplify || yarn add aws-amplify
import Amplify from "aws-amplify"Amplify.configure({
API: {
graphql_endpoint: 'https:/www.example.com/my-graphql-endpoint'
}
})
Amplify.configure({
API: {
graphql_endpoint: 'https:/www.example.com/my-graphql-endpoint',
graphql_headers: async () => ({
'My-Custom-Header': 'my value'
})
}
});

Setting up a GraphQL API

let myAppConfig = {
'aws_appsync_graphqlEndpoint': 'https://xxxxxx.appsync-api.us-east-1.amazonaws.com/graphql',
'aws_appsync_region': 'us-east-1',
'aws_appsync_authenticationType': 'API_KEY',
'aws_appsync_apiKey': 'da2-xxxxxxxxxxxxxxxxxxxxxxxxxx'
}
Amplify.configure(aws_config)

Queries

  1. Defining the query using template literals:
const ListEvents = `query ListEvents {
listEvents {
items {
id
where
description
}
}
}`
import { API, graphqlOperation } from 'aws-amplify'const allEvents = await API.graphql(graphqlOperation(ListEvents))
const oneEvent = await API.graphql(graphqlOperation(GetEvent, { id: 'some id' }))

Mutations

const CreateEvent = `mutation CreateEvent($name: String!, $when: String!, $where: String!, $description: String!) {
createEvent(name: $name, when: $when, where: $where, description: $description) {
id
name
where
when
description
}
}`;
import { API, graphqlOperation } from 'aws-amplify'const eventDetails = {
name: 'Party tonight!',
when: '8:00pm',
where: 'Ballroom',
decription: 'Coming together as a team!'
};

const newEvent = await API.graphql(graphqlOperation(CreateEvent, eventDetails));

Subscriptions

const SubscribeToEvents = `subscription subscribeToEvents {
subscribeToEvents {
id
name
when
where
}
}`
const subscription = API.graphql(
graphqlOperation(SubscribeToEvents)
).subscribe({
next: (eventData) => console.log(eventData)
});
subscription.unsubscribe()

React components

npm i aws-amplify-react || yarn add aws-amplify-react
import { Connect } from 'aws-amplify-react'const ListEvents = `query ListEvents {
listEvents {
items {
id
name
description
}
}
}`
// in your render method:
<Connect query={graphqlOperation(ListEvents)}>
{({ data: { listEvents } }) => (
<ListView events={listEvents.items} />
)}
</Connect>

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nader Dabit

Nader Dabit

12.2K Followers

Developer Relations Engineer at Edge & Node working with The Graph Protocol