Page updated Apr 10, 2024

Create, update, and delete application data

In this guide, you will learn how to create, update, and delete your data using Amplify Libraries' GraphQL client.

Before you begin, you will need:

Run mutations to create, update, and delete application data

In GraphQL, mutations are APIs that are used to create, update, or delete data. This is different than queries, which are used to read the data but not change it. The following examples demonstrate how you can create, update, and delete items using the Amplify GraphQL client.

Create an item

You can run a GraphQL mutation with Amplify.API.mutate to create an item.

Make sure you have the following imports at the top of your file:

1import Amplify
1func createTodo() async {
2 // Retrieve your Todo using Amplify.API.query
3 var todo = Todo(name: "my first todo", description: "todo description")
4 todo.description = "created description"
5 do {
6 let result = try await Amplify.API.mutate(request: .create(todo))
7 switch result {
8 case .success(let todo):
9 print("Successfully created todo: \(todo)")
10 case .failure(let error):
11 print("Got failed result with \(error.errorDescription)")
12 }
13 } catch let error as APIError {
14 print("Failed to create todo: ", error)
15 } catch {
16 print("Unexpected error: \(error)")
17 }
18}

You can run a GraphQL mutation with Amplify.API.mutate. Make sure you have the following imports at the top of your file:

1import Amplify
2import Combine
1func createTodo() -> AnyCancellable {
2 // Retrieve your Todo using Amplify.API.query
3 var todo = Todo(name: "my first todo", description: "todo description")
4 todo.description = "created description"
5 let todoCreated = todo
6 let sink = Amplify.Publisher.create {
7 try await Amplify.API.mutate(request: .create(todoCreated))
8 }
9 .sink {
10 if case let .failure(error) = $0 {
11 print("Got failed event with error \(error)")
12 }
13 }
14 receiveValue: { result in
15 switch result {
16 case .success(let todo):
17 print("Successfully created todo: \(todo)")
18 case .failure(let error):
19 print("Got failed result with \(error.errorDescription)")
20 }
21 }
22 return sink
23}

Update an item

To update data, replace the request with .update.

1try await Amplify.API.mutate(request: .update(todo))

Delete an item

To delete data, replace the request with .delete.

1try await Amplify.API.mutate(request: .delete(todo))

Conclusion

Congratulations! You have finished the Create, update, and delete application data guide. In this guide, you created, updated, and deleted your app data through the GraphQL API.

Next steps

Our recommended next steps include using the API to query data and subscribe to real-time events to look for mutations in your data. Some resources that will help with this work include: