Read data
Your AWS Amplify app reads the rows of your tables through the Amplify backend data API, with the client SDK or with HTTP requests. Reads use PostgREST-compatible queries. A read returns the rows allowed by the grants and row-level security (RLS) policies that you configured. To insert, update, upsert or delete rows, see Write data.
Before you begin
You need the following:
-
A table with a grant and a
selectpolicy for the role that reads it, added in a migration. The examples use anotestable with the columnsid,owner_id,bodyandcreated_at. For more information about grants and policies, see Secure your data. -
The client SDK,
@aws-amplifygen3/backend-client-js, in your app. For more information about installing it, see the client SDK READMEon GitHub.
Create a client with the backend URL and the publishable key:
import { createClient } from '@aws-amplifygen3/backend-client-js' const backend = createClient(backendUrl, publishableKey)
The client sends its calls as a visitor until a user signs in. After that, it sends the user’s token with every call. For more information about roles, see API keys and roles. To read every user’s rows, call the data API from server code, and sign each call with AWS credentials. For more information, see Call the backend with full access.
Every call returns an object with data, error, count, status, statusText and success. Check error. When the RLS policies that you configured match no rows, data is [] and error is null.
Select rows
Pass select the columns to return, or '*' for every column:
const { data, error } = await backend.from('notes').select('id, body') if (error) throw error
To read one row, add .single(). It returns the error PGRST116 when zero rows or several rows match. When the row might not exist, use .maybeSingle():
const { data: note, error } = await backend.from('notes').select('*').eq('id', 1).maybeSingle()
Filter rows
Add filters after select. A row must match every filter that you chain. In an HTTP request, each filter is a query parameter:
| SDK method | HTTP parameter | Returns rows where |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
The value is above, at least, below or at most the one given |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The array or |
|
|
|
The array holds nothing but |
|
|
|
The array holds |
|
|
|
|
|
|
|
The filter doesn’t match |
|
|
|
Either filter matches |
% matches any characters in a pattern. Write * for % in an HTTP request. To read or filter on a field of a json or jsonb column, use -> for a JSON value or ->> for text, such as select('id, meta->>color') or .eq('meta->>color', 'red'). Without a type, .textSearch uses to_tsquery syntax. The types plain, phrase and websearch use plainto_tsquery, phraseto_tsquery and websearch_to_tsquery, and the config option names the text search configuration, such as english. The SDK’s query builder follows postgrest-js 2.x and supports the same filters. For more information about the operators, see PostgREST operators
Count rows
To count rows without reading them, pass count and head:
const { count, error } = await backend.from('notes').select('*', { count: 'exact', head: true })
The count includes only the rows that the caller can read. An exact count reads every one of those rows, so it’s slow on a large table. A request for a planned or estimated count gets 400 and the code COUNT_NOT_SUPPORTED. To count over HTTP, send Prefer: count=exact, and read the total from the Content-Range response header, such as 0-49/6001.
Sort and page through rows
Sort the rows with .order, and read one page at a time with .range:
const { data, error } = await backend .from('notes') .select('id, body, created_at') .order('created_at', { ascending: false }) // nullsFirst: true puts null values first .range(0, 49) // rows 1 to 50; .range(50, 99) reads the next 50
The same page over HTTP is order=created_at.desc&limit=50&offset=0. Use limit and offset, because the data API doesn’t page by the Range header. To read only the first 10 rows, use .limit(10). Sort every paged read, so that each page starts where the previous one ended.
The database reads and skips every row before the offset. To read pages with a large offset, sort by id from highest to lowest with .order('id', { ascending: false }), and filter each page with .lt('id', lastId), where lastId is the last id on the previous page.
Read more than 1,000 rows
One read returns at most 1,000 rows, for every role and every backend, and you can’t change the limit. A select with no limit or a larger one succeeds and returns 1,000 rows. When a read returns exactly 1,000 rows, more rows might exist.
The Content-Range response header has the range of rows returned, such as 0-999/*. To find out whether more rows exist, ask for an exact count. The header then also has the total, such as 0-999/6001, and the status is 206 Partial Content.
To read every row, page through them with .range. .range(1000, 1999) returns rows 1,001 to 2,000. For more information, see Sort and page through rows.
Read related tables
To read rows with their related rows in one request, name the related table in select. The data API joins the two tables on a foreign key. In the following example, items.list_id references lists.id:
const { data, error } = await backend.from('lists').select('id, name, items(id, body)')
The same read over HTTP is GET /rest/lists?select=id,name,items(id,body). The data API reads items as the same caller, so items needs its own grant and select policy. A read on items with select('id, body, lists(name)') returns each item’s list as an object, or null.
A read returns at most 1,000 items for each list, and the response headers don’t show whether items were left out. To read more, query the related table on its own and page through it.
Filter, sort and limit related rows
A filter on a related table filters only the related rows. The following read returns every list, including lists with no open items, and each list holds only its open items:
const { data, error } = await backend.from('lists').select('id, name, items(id, body)').eq('items.done', false)
To return only the lists that have an open item, add !inner after the table name: items!inner(id, body). The HTTP form is select=id,name,items!inner(id,body)&items.done=eq.false.
To sort or limit the related rows, pass referencedTable:
const { data, error } = await backend .from('lists') .select('id, name, items(id, body, created_at)') .order('created_at', { referencedTable: 'items', ascending: false }) // HTTP: items.order=created_at.desc .limit(5, { referencedTable: 'items' }) // HTTP: items.limit=5
Choose a foreign key
When two foreign keys join the same tables, the read fails with PGRST201. For example, sender_id and recipient_id on messages both reference profiles. Name the foreign key column after !, and give each embedded table its own name:
const { data, error } = await backend .from('messages') .select('id, body, sender:profiles!sender_id(name), recipient:profiles!recipient_id(name)')
Read data over HTTP
To read data without the SDK, send a GET request to /rest/<table>, with the filters as query parameters. Run the following command to read the 20 newest notes:
curl -s "$API/rest/notes?select=id,body&order=created_at.desc&limit=20" \ -H "apikey: $KEY" -H "Authorization: Bearer $JWT"
For more information about the backend URL, the publishable key, user tokens and headers, see Call the data API over HTTP.
Read errors
| Error | Cause | Fix |
|---|---|---|
|
|
The |
Change the policies in a new migration |
|
|
The table has no grant for the caller’s role |
In a new migration, grant |
|
|
The table doesn’t exist, or its migration isn’t applied |
Apply the migration |
|
|
A column in |
Fix the column name |
|
|
|
Use |
|
|
Two foreign keys join the embedded tables |
Name the foreign key after |
|
|
The read asked for a planned or estimated count |
Use |
For more information about other error codes, see Data API errors.