Advanced workflows
This section describes different use cases for constructing your own custom GraphQL requests and how to approach it. You may want to construct your own GraphQL request if you want to
- retrieve only a subset of the data to reduce data transfer
- retrieve nested objects at a depth that you choose
- combine multiple operations into a single request
- send custom headers to your AppSync endpoint
A GraphQL request is automatically generated for you when using AWSAPIPlugin with the existing workflow. For example, if you have a Todo model, a mutation request to save the Todo will look like this:
Future<void> createAndMutateTodo() async { final todo = Todo(name: 'my first todo', description: 'todo description'); final request = ModelMutations.create(todo); final response = await Amplify.API.mutate(request: request).response; safePrint('Response: $response');}
Underneath the covers, a request is generated with a GraphQL document and variables and sent to the AppSync service.
{ "query": "mutation createTodo($input: CreateTodoInput!) { createTodo(input: $input) { id name description } }", "variables": "{ "input": { "id": "[UNIQUE-ID]", "name": "my first todo", "description": "todo description" } }}
The different parts of the document are described as follows
mutation
- the operation type to be performed, other operation types arequery
andsubscription
createTodo($input: CreateTodoInput!)
- the name and input of the operation.$input: CreateTodoInput!
- the input of typeCreateTodoInput!
referencing the variables containing JSON inputcreateTodo(input: $input)
- the mutation operation which takes a variable input from$input
- the selection set containing
id
,name
, anddescription
are fields specified to be returned in the response
You can learn more about the structure of a request from GraphQL Query Language and AppSync documentation. To test out constructing your own requests, open the AppSync console using amplify console api
and navigate to the Queries tab.
Subset of data
The selection set of the document specifies which fields are returned in the response. For example, if you are displaying a view of the Todo without the description, you can construct the document to omit the field. You can learn more about selection sets here.
query getTodo($id: ID!) { getTodo(id: $id) { id name }}
The response data will look like this
{ "data": { "getTodo": { "id": "111", "name": "my first todo" } }}
First, create your own GraphQLRequest
const getTodo = 'getTodo';const graphQLDocument = '''query GetTodo(\$id: ID!) { $getTodo(id: \$id) { id name }}''';final getTodoRequest = GraphQLRequest<Todo>( document: graphQLDocument, modelType: Todo.classType, variables: <String, String>{'id': someTodoId}, decodePath: getTodo,);
The decodePath
specifies which part of the response to deserialize to the modelType
. You'll need to specify the operation name (as decodePath
) and modelType
to deserialize the object at "data.getTodo" successfully into a Todo
model.
Then, query for the Todo by a todo id:
Future<void> queryTodo(GraphQLRequest<Todo> getTodoRequest) async { final response = await Amplify.API.query(request: getTodoRequest).response; safePrint('Response: $response');}
Nested Data
If you have a relational model, you can retrieve the nested object by creating a GraphQLRequest
with a selection set containing the nested object's fields. For example, in this schema, the Post can contain multiple comments and notes.
enum PostStatus { ACTIVE INACTIVE}
type Post @model { id: ID! title: String! rating: Int! status: PostStatus! comments: [Comment] @hasMany(indexName: "byPost", fields: ["id"]) notes: [Note] @hasMany(indexName: "byNote", fields: ["id"])}
type Comment @model { id: ID! postID: ID! @index(name: "byPost", sortKeyFields: ["content"]) post: Post! @belongsTo(fields: ["postID"]) content: String!}
type Note @model { id: ID! postID: ID! @index(name: "byNote", sortKeyFields: ["content"]) post: Post! @belongsTo(fields: ["postID"]) content: String!}
If you only want to retrieve the comments, without the notes, create a GraphQLRequest
for the Post with nested fields only containing the comment fields.
const getPost = 'getPost';const graphQLDocument = '''query GetPost(\$id: ID!) { $getPost(id: \$id) { id title rating status comments { items { id postID content } } }}''';final getPostRequest = GraphQLRequest<Post>( document: graphQLDocument, modelType: Post.classType, variables: <String, String>{'id': somePostId}, decodePath: getPost,);
Then, query for the Post
with nested comments included in decoded response:
Future<void> queryPostWithNestedComments( GraphQLRequest<Post> getPostRequest,) async { final response = await Amplify.API.query(request: getPostRequest).response; safePrint('Response $response');}
Combining Multiple Operations
When you want to perform more than one operation in a single request, you can place them within the same document. For example, to retrieve a Post and a Todo
const getTodo = 'getTodo';const getPost = 'getPost';const graphQLDocument = ''' query GetPostAndTodo(\$todoId: ID!, \$postId: ID!) { $getTodo(id: \$todoId) { id name } $getPost(id: \$postId) { id title rating } }
''';final multiOperationRequest = GraphQLRequest<String>( document: graphQLDocument, variables: <String, String>{'todoId': someTodoId, 'postId': somePostId},);
Notice here that modelType
and decodePath
are omitted. When these decoding variables are omitted, the plugin simply returns the result as a raw String
from the response.
Once you have the response data in a String
, you can parse it using json.decode()
and pass the resulting Map
to the model's fromJson()
method to create an instance of the model.
// Do not forget to add this to imports for json.decodeimport 'dart:convert';
...
Future<void> queryMultiOperationRequest( GraphQLRequest<String> operation,) async { final response = await Amplify.API.query(request: multiOperationRequest).response; if (response.data != null) { final jsonData = (json.decode(response.data) as Map).cast<String, Object?>(); final post = Post.fromJson((jsonData[getPost] as Map).cast<String, Object?>); final todo = Todo.fromJson((jsonData[getTodo] as Map).cast<String, Object?>); }}
Adding Headers to Outgoing Requests
By default, the API plugin includes appropriate authorization headers on your outgoing requests. However, you may have an advanced use case where you wish to send additional request headers to AppSync.
The simplest option for GraphQL requests is to use the headers
property of a GraphQLRequest
.
Future<void> queryWithCustomHeaders() async { final operation = Amplify.API.query<String>( request: GraphQLRequest( document: graphQLDocumentString, headers: {'customHeader': 'someValue'}, ), ); final response = await operation.response; final data = response.data; safePrint('data: $data');}
Another option is to use the baseHttpClient
property of the API plugin which can customize headers or otherwise alter HTTP functionality for all HTTP calls.
// First create a custom HTTP client implementation to extend HTTP functionality.class MyHttpRequestInterceptor extends AWSBaseHttpClient { Future<AWSBaseHttpRequest> transformRequest( AWSBaseHttpRequest request, ) async { request.headers.putIfAbsent('customHeader', () => 'someValue'); return request; }}
// Then you can pass an instance of this client to `baseHttpClient` when you configure Amplify.await Amplify.addPlugins([ AmplifyAPI(baseHttpClient: MyHttpRequestInterceptor()),]);