Run Queries and Mutations - AWS AppSync

Run Queries and Mutations

Now that you have taken a tour of the console it’s time to get more familiar with GraphQL. In the AWS AppSync console choose the Queries tab on the left hand side. The pane on the right side enables you to click through the operations, including queries, mutations, and subscriptions that your schema has exposed. Choose the Mutation node to see a mutation. You can add a new event to it as follows: createEvent(....):Event. Use this to add something to your database with GraphQL.

Add Data with a GraphQL Mutation

Your first step is to add more data with a GraphQL mutation. To do this, you use the mutation keyword and pass in the appropriate arguments (similar to how a function works). You can also select which data you want returned in the response by putting the fields inside curly braces. To get started, copy the following into the query editor and then choose Run:

mutation add { createEvent( name:"My first GraphQL event" where:"Day 1" when:"Friday night" description:"Catching up with friends" ){ id name where when description } }

The record is parsed by the GraphQL engine and inserted into your Amazon DynamoDB table by a resolver that is connected to a data source. (You can check this in the DynamoDB console.) Notice that you didn’t need to pass in an id. An id is generated and returned in the results specified between the curly braces. As a best practice, this sample uses an autoId() function in a GraphQL resolver for the partition key set on your DynamoDB resources. For now, just make a note of the returned id value, which you’ll use in the next section.

Retrieve Data with a GraphQL Query

Now that there is a record in your database, you’ll get results when you run a query. One of the main advantages of GraphQL is the ability to specify the exact data requirements that your application has in a query. This time, only add a few of the fields inside the curly braces, pass the id argument to getEvent(), and then choose Run at the top:

query get { getEvent(id:"XXXXXX-XXXX-XXXXXXX-XXXX-XXXXXXXXX"){ name where description } }

This time, only the fields you specified are returned. You can also try listing all events as follows:

query getAllEvents { listEvents{ items{ id name when } } }

This time the query shows nested types and gives the query a friendly name (getAllEvents), which is optional. Experiment by adding or removing, and then running the query again. When you’re done, it’s time to connect a client application.

Running an Application

Now that your API is working, you can use a client application to interact with it. To get started, skip to Building Client Applications. Otherwise, see the other options below.

Next Steps

Now that you’ve run through the preconfigured schema, you can choose to build an API from scratch, incorporate an existing data source, or build a client application. For more information, see the following sections: