

# Write data

Your AWS Amplify app inserts, updates, upserts and deletes the rows of your tables through the Amplify backend data API, with the client SDK or with HTTP requests. Each write changes only the rows allowed by the grants and row-level security (RLS) policies that you configured.

## Before you begin
<a name="_before_you_begin"></a>

You need the following:
+ A table with a grant and a policy for each write that your app makes, added in a migration. Updates, upserts and deletes, and any write that returns the changed rows (with `.select()` or the header `Prefer: return=representation`), also need a `select` policy. Without one, even an insert that returns its row fails with `409` `WRITE_CONFLICT`. The examples use a `notes` table with the columns `id`, `owner_id`, `body` and `created_at`. For more information about grants and policies, see [Secure your data](backend-rls.md).
+ A client created with `createClient(backendUrl, publishableKey)` from `@aws-amplifygen3/backend-client-js`. For more information about the client and the filters that pick rows, see [Read data](backend-data-api-query.md).

To change every user’s rows, call the data API from server code, such as a scheduled job, and sign each call with AWS credentials, using AWS Signature Version 4 (SigV4). Never put AWS credentials in browser code. For more information about signing calls, see [Call the backend with full access](backend-server-code.md#backend-server-code-full-access).

## Get the changed rows back
<a name="_get_the_changed_rows_back"></a>

A write returns the rows that it changed only when you ask for them. With the SDK, add `.select()` after the write. Over HTTP, send the header `Prefer: return=representation`.

Check the rows that come back. An update or delete that returns `[]` changed nothing, and `error` is `null`. Either the RLS policies that you configured matched no row, or the filter matched nothing.

When you ask for the changed rows, a write returns every one of them. The 1,000-row limit applies only to reads.

## Insert rows
<a name="_insert_rows"></a>

Pass `insert` the new row:

```typescript
const { data, error } = await backend.from('notes').insert({ body: 'hello' }).select()
```

The migration that creates the `notes` table sets `owner_id text not null default auth.uid()`, so your app doesn’t send `owner_id`. To insert several rows in one request, pass an array, such as `insert([{ body: 'one' }, { body: 'two' }])`.

## Update rows
<a name="_update_rows"></a>

Pick the rows with a filter, and pass the new values:

```typescript
const { data, error } = await backend.from('notes').update({ body: 'edited' }).eq('id', 1).select()
```

An update changes only the rows that the caller can select. With no `select` policy, the update changes no rows and returns `[]`.

## Upsert rows
<a name="_upsert_rows"></a>

An upsert inserts a row, or updates the existing row whose unique column matches:

```typescript
const { data, error } = await backend
  .from('profiles')
  .upsert({ id, name }, { onConflict: 'id' }) // the id column needs a unique constraint
  .select()
```

The caller needs grants and policies for `select`, `insert` and `update`. With no `select` policy, every upsert fails with `409` `WRITE_CONFLICT`, even for a new row.

## Delete rows
<a name="_delete_rows"></a>

Pick the rows with a filter, and call `delete`:

```typescript
const { data, error } = await backend.from('notes').delete().eq('id', 1).select()
```

The `data` array holds the deleted rows. A delete also changes only the rows that the caller can select.

## Write data over HTTP
<a name="_write_data_over_http"></a>

Send the `apikey` header, the user’s token in `Authorization: Bearer <token>`, and a JSON body with each write. For more information about setting `API`, `KEY` and `JWT`, see [Call the data API over HTTP](backend-data-api-http.md).

Run the following commands to insert, update, upsert and delete rows:

```bash
H=(-H "apikey: $KEY" -H "Authorization: Bearer $JWT" -H 'content-type: application/json' -H 'Prefer: return=representation')

# Insert. Send a JSON array to insert several rows.
# Keep the new row's id: it's often not 1.
ID=$(curl -s -X POST "$API/rest/notes" "${H[@]}" -d '{"body":"hello"}' | jq -r '.[0].id')

# Update the rows that the filter matches.
curl -s -X PATCH "$API/rest/notes?id=eq.$ID" "${H[@]}" -d '{"body":"edited"}'

# Upsert on the unique id column.
curl -s -X POST "$API/rest/profiles?on_conflict=id" -H "apikey: $KEY" -H "Authorization: Bearer $JWT" \
  -H 'content-type: application/json' -H 'Prefer: resolution=merge-duplicates,return=representation' \
  -d '{"id":"u1","name":"Ana"}'

# Delete the rows that the filter matches.
curl -s -X DELETE "$API/rest/notes?id=eq.$ID" "${H[@]}"
```

A request body can be at most 10 MiB, and a larger one gets `413` and the code `PAYLOAD_TOO_LARGE`. A request that you sign with AWS credentials for full access can have a body of at most 1 MiB. To write more data, split it into several requests.

## Write errors
<a name="_write_errors"></a>


| Error | Cause | Fix | 
| --- | --- | --- | 
|  `[]` from an update or delete | The RLS policies that you configured match no row, the table has no `select` policy, or the filter matched nothing | Check the filter and the table’s `select`, `update` and `delete` policies | 
|  `WRITE_CONFLICT` (`409`) | The write breaks a unique, foreign key or exclusion constraint, or the RLS policies that you configured don’t allow it: the table has no `insert` policy, the new row fails a policy’s `WITH CHECK`, or a write that returns its rows has no `select` policy | The `409` body names no constraint or policy, and only a `service_role` request gets the original SQLSTATE, such as `23505`. To find the cause, read the database log with `aws amplifygen3 logs get --log-type database --env <env>`. This command needs database logs delivered to CloudWatch, and reports when delivery is off. To check the setting, run `aws amplifygen3 logs-config get`. For more information about the local backend’s log, see [Local database](backend-local-database.md)  | 
|  `42501` (`401` signed out, `403` signed in) | The table has no grant for the write | In a new migration, grant the operation to the role that makes the write | 
|  `PAYLOAD_TOO_LARGE` (`413`) | The request body is over 10 MiB | Split the write into several requests | 

For a `409`, show your users a message such as "Couldn’t save. That might already exist." For more information about other error codes, see [Data API errors](backend-data-api-errors.md).