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 your data.

1Future<void> createTodo() async {
2 try {
3 final todo = Todo(name: 'my first todo', description: 'todo description');
4 final request = ModelMutations.create(todo);
5 final response = await Amplify.API.mutate(request: request).response;
6
7 final createdTodo = response.data;
8 if (createdTodo == null) {
9 safePrint('errors: ${response.errors}');
10 return;
11 }
12 safePrint('Mutation result: ${createdTodo.name}');
13 } on ApiException catch (e) {
14 safePrint('Mutation failed: $e');
15 }
16}

Update an item

To update the Todo with a new name:

1Future<void> updateTodo(Todo originalTodo) async {
2 final todoWithNewName = originalTodo.copyWith(name: 'new name');
3
4 final request = ModelMutations.update(todoWithNewName);
5 final response = await Amplify.API.mutate(request: request).response;
6 safePrint('Response: $response');
7}

Delete an item

To delete the Todo:

1Future<void> deleteTodo(Todo todoToDelete) async {
2 final request = ModelMutations.delete(todoToDelete);
3 final response = await Amplify.API.mutate(request: request).response;
4 safePrint('Response: $response');
5}

Or you can delete by ID, which is ideal if you do not have the instance in memory yet:

1Future<void> deleteTodoById(Todo todoToDelete) async {
2 final request = ModelMutations.deleteById(
3 Todo.classType,
4 TodoModelIdentifier(id: '8e0dd2fc-2f4a-4dc4-b47f-2052eda10775'),
5 );
6 final response = await Amplify.API.mutate(request: request).response;
7 safePrint('Response: $response');
8}

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: