Chrysolites Tech Academy

Photo Social App with FlutterFlow and Supabase · Course book

Chapter 16: API Calls and Custom Data Types

Pairs with Lesson 16: Search with API Calls to Supabase

Simple Search filters posts the phone has already downloaded, which is quick but cannot find what was never fetched. To search every post in a growing app, the database itself must do the searching. This chapter rebuilds the search feature with an API call from FlutterFlow straight to Supabase's REST interface: it explains what that interface is, how to set up an API call with its address, headers and variables, how pattern matching works in the request, worked out by hand, how a custom data type describes the JSON that comes back, how the results reach the grid, and how to test and secure the whole thing.

Supabase's REST interface

Every table and view in a Supabase project is automatically available through a REST API: a set of web addresses that accept HTTP requests and return JSON. FlutterFlow's built-in Supabase actions use this interface behind the scenes. Calling it directly with an API call gives full control over the request, including filters that the visual query builder does not offer, and the same technique works with any other web service an app might need later, such as a weather service or an artificial intelligence model.

A request to read rows is a GET request to the project's address followed by /rest/v1/ and the table or view name. Query parameters choose the columns, filter the rows, order them and limit their number. Two headers identify the caller: apikey, carrying the project's public anon key, and Authorization, carrying Bearer followed by the signed-in user's access token, so that row level security policies apply exactly as they do for built-in actions.

Part of the requestExamplePurpose
Method and pathGET /rest/v1/posts_with_authorsRead rows from the view
selectselect=id,image_url,caption,usernameReturn only the columns the grid needs
Filtercaption=ilike.*sunset*Captions containing "sunset", any capitalisation
order and limitorder=created_at.desc&limit=30Newest matches first, at most 30
Headersapikey and Authorization: Bearer tokenIdentify the project and the user

Setting up the API call

In FlutterFlow's API Calls section, a new call is given a name, such as searchPosts, the method GET and the base address of the project's REST interface. The search term must change with every search, so it becomes a variable of the call, written into the query parameters with FlutterFlow's variable syntax so that each search fills it in. The headers are added once: the anon key can be stored as a constant, while the user's token is passed as a variable from the authenticated user's details.

FlutterFlow can test a call from its editor: entering a sample term, such as "sunset", sends the request and shows the raw JSON response. That test is the quickest way to find mistakes such as a misspelt column name, a missing header or a filter in the wrong format, before connecting the call to any page. Grouping related calls, for example all calls to the Supabase interface, into an API group lets them share the base address and headers.

Understanding the response codes helps when a test fails. A 200 status means the request worked, even if the list it returns is empty. A 400 usually means the query itself is malformed, such as a filter with a typo or a column that does not exist, and the response body explains which. A 401 means the token is missing or has expired, so the user must sign in again or the token must be refreshed. A 404 typically means the table or view name in the path is wrong, or that a newly created view has not yet been exposed to the API. Reading the status and the message in FlutterFlow's test panel usually points straight to the cause.

Access tokens expire, typically after an hour, and the Supabase client refreshes them automatically. Because the API call reads the current token from the authenticated user each time it runs, rather than storing a copy, it always sends a valid one. Hard-coding a token copied during testing is a common mistake: the call works for an hour and then mysteriously fails.

FlutterFlow app searchPosts(term)headers: apikey,Authorization: Bearerparse JSON intoList<PostResult>bind to results grid Supabase REST check tokenapply row level securityfilter with ilikeorder, limit 30use indexesreturn JSON array GET /rest/v1/posts_with_authors ?caption=ilike.*sunset*&limit=30 [ {"id":..., "caption":"Sunset pier", ...}, ... ] only the matches travel back to the phone
Figure 16.1 — A search through the REST interface. The database filters, orders and limits; the app parses the returned JSON and shows it.

Pattern matching in the request

The filter ilike performs a case-insensitive pattern match, like SQL's ILIKE. In the REST interface, an asterisk stands for "any characters", so *sunset* matches any caption containing "sunset" anywhere, whether "Sunset pier", "golden SUNSET" or "sunsets". Searching both captions and usernames uses the or parameter, which accepts several conditions, any of which may match.

Values placed in an address must be URL-encoded: characters with special meanings, such as spaces, commas and ampersands, are replaced with a percent sign and two hexadecimal digits, so that the search term cannot break the request or be misread as another parameter. FlutterFlow encodes variables for you, but it is worth understanding what it does.

Worked example. A user searches for beach day. The filter becomes caption=ilike.*beach day*, and URL-encoding replaces the space with %20, giving caption=ilike.*beach%20day*; the asterisks are safe as they are. A term containing an ampersand, such as fish & chips, encodes the ampersand as %26, since an unencoded & would start a new parameter and silently cut the search short. If each result row in the response is about 250 bytes, a search returning the limit of 30 rows transfers about 30 × 250 = 7,500 bytes, under 8 KB, whether the table holds a thousand posts or a million.

Pattern matching with a leading wildcard cannot use an ordinary index, so on very large tables Supabase's full-text search, which matches whole words using a special index, or a trigram index, which speeds up ilike searches, keeps searches fast. For an app of modest size, plain ilike on a few thousand rows is perfectly quick. Unlike the fuzzy Simple Search, ilike does not forgive typos: "sunst" finds nothing, so a server-side similarity search, also available through trigram functions, is the next step if typo tolerance matters.

Custom data types and the results

The response is a JSON array, one object per matching row, with fields named after the selected columns. To use it comfortably, FlutterFlow lets you define a custom data type, such as PostResult, with fields matching the JSON: an id, an image address, a caption and a username, each with its type. The API call's response is then mapped to a list of PostResult, and every widget that displays a result can refer to its fields by name, with type checking, instead of picking values out of raw JSON with paths. FlutterFlow can generate the data type automatically from a sample response, which saves typing and avoids mismatched field names; fields that may be missing, such as a caption left empty, should be marked as optional so that a null value does not cause an error.

On the search page, submitting the search runs a Backend Call action for searchPosts with the term, checks whether the call succeeded, and stores the parsed list in page state. The results grid is bound to that list. An unsuccessful call, for instance with no network, shows a message and a retry option; an empty list shows "No posts found". Because each call travels to the server, searching on every keystroke would send many requests, so the call runs when the user submits, or after a short pause in typing.

Testing and security

Testing compares the results with the database: search for a word that appears in a known caption, a word in mixed capitals, a word that appears nowhere and a term with a space. Check that the grid shows exactly what the Supabase table editor shows for the same filter, that tapping a result opens the right post and that the newest matches come first, even when many posts match the term.

Security works exactly as for built-in queries, because the request carries the user's token and the database applies its policies. Two points deserve care. Never put the service role key in an API call, since it bypasses every policy and would be extracted from the app. And make sure the select parameter lists only the columns the screen needs, so that a view never sends fields, such as an email address, that the user has no reason to receive. With search done, the next part builds the post detail page that every search result opens.

Practice tasks

  1. URL-encode the search terms city lights and rock & roll as they would appear in the filter.
  2. A search returns 20 rows of 300 bytes each. How much data is transferred?
  3. Write the query parameters that return the newest 25 posts whose caption contains "cafe", with only the id, image address and caption.
  4. Define a custom data type for an account search result with four fields, and give each a type.
  5. Why must the request carry the user's access token rather than only the anon key?
  6. Explain why an ilike pattern starting with a wildcard is slow on huge tables, and name two remedies.

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.