Page updated Jan 16, 2024

Advanced workflows

Amplify iOS v1 is now in Maintenance Mode until May 31st, 2024. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v1.

Please use the latest version (v2) of Amplify Library for Swift to get started.

If you are currently using v1, follow these instructions to upgrade to v2.

Amplify libraries should be used for all new cloud connected applications. If you are currently using the AWS Mobile SDK for iOS, you can access the documentation here.

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:

1let todo = Todo(name: "my first todo", description: "todo description")
2Amplify.API.mutate(request: .create(todo))

Underneath the covers, a request is generated with a GraphQL document and variables and sent to the AppSync service.

1{
2 "query": "mutation createTodo($input: CreateTodoInput!) {
3 createTodo(input: $input) {
4 id
5 name
6 description
7 }
8 }",
9 "variables": "{
10 "input": {
11 "id": "[UNIQUE-ID]",
12 "name": "my first todo",
13 "description": "todo description"
14 }
15 }
16}

The different parts of the document are described as follows

  • mutation - the operation type to be performed, other operation types are query and subscription
  • createTodo($input: CreateTodoInput!) - the name and input of the operation.
  • $input: CreateTodoInput! - the input of type CreateTodoInput! referencing the variables containing JSON input
  • createTodo(input: $input) - the mutation operation which takes a variable input from $input
  • the selection set containing id, name, and description 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.

1query getTodo($id: ID!) {
2 getTodo(id: $id) {
3 id
4 name
5 }
6}

The response data will look like this

1{
2 "data": {
3 "getTodo": {
4 "id": "111",
5 "name": "my first todo"
6 }
7 }
8}

First, create your own GraphQLRequest

1extension GraphQLRequest {
2 static func getWithoutDescription(byId id: String) -> GraphQLRequest<Todo> {
3 let operationName = "getTodo"
4 let document = """
5 query getTodo($id: ID!) {
6 \(operationName)(id: $id) {
7 id
8 name
9 }
10 }
11 """
12 return GraphQLRequest<Todo>(
13 document: document,
14 variables: ["id": id],
15 responseType: Todo.self,
16 decodePath: operationName
17 )
18 }
19}

The decode path specifies which part of the response to deserialize to the responseType. You'll need to specify the operation name to deserialize the object at "data.getTodo" successfully into a Todo model.

Then, query for the Todo by a todo id

1Amplify.API.query(request: .getWithoutDescription(byId: "[UNIQUE_ID]")) {
2 // handle result

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.

1enum PostStatus {
2 ACTIVE
3 INACTIVE
4}
5
6type Post @model {
7 id: ID!
8 title: String!
9 rating: Int!
10 status: PostStatus!
11 comments: [Comment] @hasMany(indexName: "byPost", fields: ["id"])
12 notes: [Note] @hasMany(indexName: "byNote", fields: ["id"])
13}
14
15type Comment @model {
16 id: ID!
17 postID: ID! @index(name: "byPost", sortKeyFields: ["content"])
18 post: Post! @belongsTo(fields: ["postID"])
19 content: String!
20}
21
22type Note @model {
23 id: ID!
24 postID: ID! @index(name: "byNote", sortKeyFields: ["content"])
25 post: Post! @belongsTo(fields: ["postID"])
26 content: String!
27}

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.

1extension GraphQLRequest {
2 static func getPostWithComments(byId id: String) -> GraphQLRequest<Post> {
3 let document = """
4 query getPost($id: ID!) {
5 getPost(id: $id) {
6 id
7 title
8 rating
9 status
10 comments {
11 items {
12 id
13 postID
14 content
15 }
16 }
17 }
18 }
19 """
20 return GraphQLRequest<Post>(
21 document: document,
22 variables: ["id": id],
23 responseType: Post.self,
24 decodePath: "getPost"
25 )
26 }
27}

Query with Amplify.API.query(request: .getPostWithComments(byId: "[POST_ID]")).

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

1extension GraphQLRequest {
2 static func get(byPostId postId: String, todoId: String) -> GraphQLRequest<JSONValue> {
3 let document = """
4 query get($postId: ID!, $todoId: ID!) {
5 getPost(id: $postId) {
6 id
7 title
8 rating
9 }
10 getTodo(id: $todoId) {
11 id
12 name
13 }
14 }
15 """
16 return GraphQLRequest<JSONValue>(document: document,
17 variables: ["postId": postId,
18 "todoId": todoId],
19 responseType: JSONValue.self)
20 }
21}

Notice here that JSONValue is used as the responseType. JSONValue is utility type that can be used to represent an arbitrary JSON response.

Once you have the response data in a JSONValue, you can access each object in the JSON structure by encoding it back to Data and decoding it to the expected Model.

1Amplify.API.query(request: .get(byPostId: "[POST_ID]", todoId: "[TODO_ID]")) { result in
2 switch result {
3 case .success(let response):
4 switch response {
5 case .success(let data):
6 if let todoJSON = data.value(at: "getTodo"),
7 let todoData = try? JSONEncoder().encode(todoJSON),
8 let todo = try? JSONDecoder().decode(Todo.self, from: todoData) {
9 print(todo)
10 }
11 if let postJSON = data.value(at: "getPost"),
12 let postData = try? JSONEncoder().encode(postJSON),
13 let post = try? JSONDecoder().decode(Post.self, from: postData) {
14 print(post)
15 }
16 case .failure(let errorResponse):
17 print("Response contained errors: \(errorResponse)")
18 }
19 case .failure(let apiError):
20 print("Failed with error: \(apiError)")
21 }
22}

If you have custom models or your Model has required fields that you have decided not to include in the response, you can create a Codable that conforms to the structure of the response data that you expect. From the previous example, the Codable would look like this

1struct PostAndTodoResponse: Codable {
2 public let getTodo: Todo
3 public let getPost: Post
4 struct Todo: Codable {
5 public let id: String
6 public var name: String
7 }
8 struct Post: Codable {
9 public let id: String
10 public var title: String
11 public var rating: Int
12 }
13}

Then use PostAndTodoResponse as the responseType of the GraphQLRequest instead of using JSONValue.

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.

To include custom headers in your outgoing requests, add an URLRequestInterceptor to the AWSAPIPlugin. Also specify the name of one of the APIs configured in your amplifyconfiguration.json file.

1struct CustomInterceptor: URLRequestInterceptor {
2 func intercept(_ request: URLRequest) throws -> URLRequest {
3 let nsUrlRequest = (request as NSURLRequest)
4 guard let mutableRequest = nsUrlRequest.mutableCopy() as? NSMutableURLRequest else {
5 throw APIError.unknown("Could not get mutable request", "")
6 }
7 mutableRequest.setValue("headerValue", forHTTPHeaderField: "headerKey")
8 return mutableRequest as URLRequest
9 }
10}
11let apiPlugin = try AWSAPIPlugin()
12try Amplify.addPlugin(apiPlugin)
13try Amplify.configure()
14try apiPlugin.add(interceptor: CustomInterceptor(), for: "yourApiName")