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:
import Amplify
func createTodo() async { // Retrieve your Todo using Amplify.API.query var todo = Todo(name: "my first todo", description: "todo description") todo.description = "created description" do { let result = try await Amplify.API.mutate(request: .create(todo)) switch result { case .success(let todo): print("Successfully created todo: \(todo)") case .failure(let error): print("Got failed result with \(error.errorDescription)") } } catch let error as APIError { print("Failed to create todo: ", error) } catch { print("Unexpected error: \(error)") }}
You can run a GraphQL mutation with Amplify.API.mutate
. Make sure you have the following imports at the top of your file:
import Amplifyimport Combine
func createTodo() -> AnyCancellable { // Retrieve your Todo using Amplify.API.query var todo = Todo(name: "my first todo", description: "todo description") todo.description = "created description" let todoCreated = todo let sink = Amplify.Publisher.create { try await Amplify.API.mutate(request: .create(todoCreated)) } .sink { if case let .failure(error) = $0 { print("Got failed event with error \(error)") } } receiveValue: { result in switch result { case .success(let todo): print("Successfully created todo: \(todo)") case .failure(let error): print("Got failed result with \(error.errorDescription)") } } return sink}
Update an item
To update data, replace the request with .update
.
try await Amplify.API.mutate(request: .update(todo))
Delete an item
To delete data, replace the request with .delete
.
try 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: