LogoLogo
Back to studio
  • Formsort documentation
  • โฉQuickstart
    • ๐ŸŸขGet started with Formsort
    • ๐ŸŽCore concepts
    • โ„น๏ธQuestion and content reference
    • ๐Ÿ“•Key terms
    • ๐Ÿž๏ธCreate your first flow
    • ๐Ÿ“–Add content and collect answers
      • ๐ŸคณCapture demographic data
      • โ„น๏ธAdd informational content
      • ๐Ÿ” Review your variable schema
    • ๐ŸŽจCreate a theme
      • Set brand guidelines
    • ๐ŸคนPersonalize your flow
      • ๐ŸŒŸTemplate your variables
      • ๐Ÿง Add conditional logic
      • ๐Ÿ’ซUsing conditional logic with Calculated and API variables
      • ๐Ÿ”šEnd the flow
    • ๐Ÿ”€Set up integrations
    • ๐Ÿš€Go live
      • Auditing your flow for content, functionality, and design
    • ๐Ÿ’ผCommon use cases
      • ๐Ÿ’”Disqualify responders
      • ๐Ÿ—“๏ธAdd a scheduling option
      • ๐Ÿ“„Allow responders to read and accept your company policies
  • ๐Ÿ—๏ธBuilding flows
    • Flows and variants
      • Flow starts
    • Adding content
      • Groups
      • Steps
        • Settings
        • Logic
        • Style
      • Questions
        • General Settings
        • Style
        • Address
        • Comparison
        • Confirmation
        • Date
        • Date & Time
        • Email address
        • File upload
        • Grid choice
        • Iframe
        • Image upload
        • Number
        • Payment
        • Phone number
        • Postal code
        • Question group
        • Region
        • Select
          • Providing choices via API or calculation
        • Signature
        • SSN
        • Text questions
        • Yes/No
      • Content
        • General Settings
        • Statement
        • Image
        • Video
        • Next button
        • Divider
        • Map
      • Endings
      • Using markdown
      • Using variable templating
        • Template formatting functions
      • Copy-pasting form content
      • Content library
    • Conditions and logic
      • Logical operator reference
      • Advanced logic
    • Variables (answers)
      • Variables from questions
      • Externally provided variables
      • Calculated variables
      • API lookups
      • System Library variables
      • Orphaned variables
    • Schemas
      • JSON Schemas
      • Validating flow schemas
    • Redirects
    • Styling and themes
      • CSS Reference
      • Overriding theme styling
      • Custom CSS overrides
      • Content area
      • Animations and transitions
      • Form Layout
      • Typography
        • Adobe Fonts
        • Hosting custom fonts
      • Color variables
      • Dimension variables
      • Question containers
      • Assets
      • Form Buttons
        • Select buttons
      • Inputs and dropdowns
      • Checkmarks
      • Tables
      • Sliders
      • Divider lines
      • Progress bar
      • Comparison cards
    • Variant settings
      • Form behavior for returning responders
      • Group ranking API
    • Publishing and versions
      • Preview window
      • Deploying
      • History
  • ๐Ÿ’พHandling data
    • Philosophy and data retention policy
    • Viewing form answers
    • Responder UUIDs
    • Environments
      • Loading different environments
    • Passing data in
      • URL parameters
      • POST body
      • Embed query parameters
    • Custom validators
    • Form answers and events
      • Analytics events
      • Signed requests
      • Event payload shape
      • Submission frequencies
      • Runtime error reporting
      • Admin API
      • Flow content data format
    • Integration reference
      • Amplitude
        • Amplitude cross domain tracking
      • BigQuery
      • FullStory
      • Google Analytics
        • Updating from Universal Analytics to GA4
      • Google Cloud Storage
      • Google Sheets
      • Google Tag Manager (GTM)
        • JavaScript triggered by flow events
      • Hubspot
      • Jornaya
      • Optimizely
      • PostgreSQL
      • Redshift
      • Rudderstack
      • S3
      • Salesforce
      • Segment
        • Segment Setup
        • Segment cross domain tracking
      • Stripe
      • TrustedForm
      • Webhooks
        • Zapier
  • ๐Ÿ“บGoing live
    • Custom domains
    • Built-in analytics
    • Embedding
      • Web-Embed API
        • React-embed
      • Adding authentication
      • Embedding forms in iOS and Android
      • Setting up a dev environment
    • Split testing
    • Preflight checklist
  • ๐ŸขTeams
    • Accounts
      • Roles and permissions
    • Events subscriptions
    • Workspace domain detection
Powered by GitBook
On this page
  • When are API lookups dispatched?
  • CORS considerations
  • Creating an API lookup
  • Method
  • URL
  • Result processing
  • Basic configuration settings
  • Variable type
  • Is array?
  • Calculate on Submit
  • Re-calculate on load
  • Fetch conditionally
  • Blocks advancing from current step
  • Extracting multiple fields from API response
  • Awaiting responses
  • Handling errors
  • Authentication

Was this helpful?

  1. Building flows
  2. Variables (answers)

API lookups

Store answers from API calls.

PreviousCalculated variablesNextSystem Library variables

Last updated 5 months ago

Was this helpful?

Using an API lookup, you can fetch an from a server that returns JSON responses. To make the call dynamic, the lookup can use answers collected with the flow as request headers or query parameters.

Some examples of common uses of API lookups include:

  • Finding the current price of an item.

  • Locating the closest store to a user, based on their zipcode.

  • Looking up an account ID based on a user's email.

You can also look up to make your Select components dynamic! This is defined directly at the select component.

The answers fetched in an API lookup behave just like any other variable: they can be used for , into other components, and are sent to your .

When are API lookups dispatched?

If an API answer has no dependencies (there are no templated answers within its URL), the API lookup will happen as soon as the flow loads.

If an API answer has dependencies, the API lookup will happen as soon as all of its inputs are defined, and will be re-run whenever those inputs change. If any of the inputs become undefined, the API answer will be cleared.

For more control over when the API lookup happens, you can set a condition for its evaluation with Fetch conditionally, or you can choose to wait with .

Doing a simple calculation with variables you already have present?

If you don't need fetch data from a server, you can use a to perform a calculation directly within the form flow.

CORS considerations

API-lookup http requests come directly from the responder's browser. If your server enforces restrictions (CORS), you will need to whitelist the following in the Access-Control-Allow-Origin response header:

  • <client-id>.formsort.app

  • studio.formsort.com (for testing within the studio)

Alternatively, you can enable the wildcard * origin in the Access-Control-Allow-Origin header if you would like to disable CORS restrictions.


Creating an API lookup

To configure an API lookup, in any variant go to Variables > API lookups and click Add API lookup.

Take a look at our API lookup editor settings and configurations below.

Method

You can change the REST method of the API lookup. Currently available is GET, POST, and PUT.

URL

Provide the URL of the endpoint you wish to hit in the API URL field.

Templating variables into URLs

For example, if you ask the responder for their postal code in an answer with variable name user_zip, you can use that answer to look up store locations with a URL like

https://example.com/api/stores?zip_code={{user_zip}}.

Optional parameters

The default template formatting function default values for an API variable's URL. If you have a lookup like

https://example.com?age={{age}}&promo={{promo | default ""}}

then the API will be dispatched whenever the age variable is defined. Promo does not need to be defined by the user, since it has a default value of an empty string ("").

Result processing

If your API returns a payload with a shape that isn't directly the desired variable type, you can process the result within Formsort to avoid having to change the shape of your API responses.

For the following result processing examples, consider the below JSON response payload for a list of stores:

Sample JSON response body
// Object 
Result: {
  "person": {
    "name": {
     firstName: "Frodo"
     lastName: "Baggins"
    }
    "location": "The Shire"
  }
}

// Array 
[
  {
    address: "123 Main St",
    isOpen: false,
  },
  {
    address: "4 Back St",
    isOpen: true,
  }
]

JSON accessor

If the answer you want to access can be accessed directly with keys and indices, you can write out the path to the desired data with the JSON accessor. Formsort opens an object upon receipt, so it is unnecessary to include the object name in the accessor function.

For example, in the object above, Result.person.location person.location would return "The Shire". You can drill down a level as well: person.name.firstName would return "Frodo".

In the array example, 0.address would return the address of the first result, which in the above example would be "123 Main St".

Mapping function

This function has an argument, res, which is the body of the raw JSON object returned from the server. It should return the desired answer.

For example, if we'd like to access the address of the first open address from the response above, the mapping function would be:

const openStores = res.filter(function(store) { return store.isOpen });
if (openStores.length) {
  return openStores[0].address;
}
return "undefined";

... which would result in "4 Back st".

The getter function will only be evaluated for a successful response. If the server returns any kind of 400 or 500 response, it will not be evaluated.


Basic configuration settings

Variable type

Is array?

This needs to be set you expect the response to contain multiple answers in an array format.

Calculate on Submit

As stated earlier, the API lookup will be dispatched either immediately if there are no variable dependencies templated into the Request Headers or URL query parameters, or as soon as the templated variables are all defined by the user.

To have the API lookup wait until the user proceeds from the past the step where the last variable is defined, enable calculate on submit.

Re-calculate on load

If an API answer was retrieved in a previous session, and the responder returns to the flow, the default behavior is not to re-fetch the answer.

To always fetch the answer on load, enable Re-calculate on load. This is useful for situations when calculated answers are not idempotent, meaning that repeated invocations do not result in the same result, such as answers depending on an API response that changes over time.

Fetch conditionally

Blocks advancing from current step


Extracting multiple fields from API response

Sometimes, you may need to extract multiple fields from a JSON response body. Imagine an endpoint like GET /userLookup?email={{email}} . This endpoint takes the email address value from the email query param. And, if the email address is found in the database, returns the id and name associated with that email. In many cases, you may need to extract both fields -- id and name -- from the response body.

// Sample JSON response body: GET /userLookup?email={{email}}
[
  {
    id: 1234,
    name: "Shinji Ikari",
  }
]

To extract multiple fields from a single JSON response object, you need to create multiple API variables: one API variable per field. Of course, you likely would prefer not to have to make a separate API call for each field. So, to avoid making multiple API requests when using multiple API variables, simply give every API variable the same URL string and query params.

By creating multiple API variables with the same URL string and query params, a single request to the given URL is made. However, the response is processed by every API variable with that URL string and query params signature. So, by using different JSON accessors or Mapping Functions (see above) for each API variable, you can extract different fields. Continuing the example above, we could use the set of API variables below to successfully retrieve the id and name fields. Note that both API variables are the same, except for their accessors. This will result in a single API request, but allow us to retrieve both fields.

// API variable 1:
Variable Name: responder_id
URL: /userLookup
Query params: email={{email}}
JSON accessor [0].id

// API variable 2:
Variable Name: responder_name
URL: /userLookup
Query params: email={{email}}
JSON accessor [0].name

If the API variables have different conditions for the Is Conditional? field, whichever API variable has their conditions met first will be the API variable which gets to make the API request. Whatever response is received from that request will be used across all other API variables with matching API URL string and query params.


Awaiting responses

If there is a pending API answer lookup, and the user is trying to advance to a step that uses the resultant answer, a loading indicator will be displayed while they await the result of the lookup.

Avoiding the loading spinner

Consider interleaving steps that provide inputs for API answers with steps that contain static content, or content orthogonal to the API lookup.

That way, even if an API request is slow, it will not matter, as the user will be viewing other content while the request happens in the background.

Handling errors

If an API answer request fails, or returns an invalid response, the answer will be undefined, and the answer will be marked as failed.

Authentication

Additionally, if you are using to host your flows, you will need to whitelist those domains.

API lookups are created inside of are local to those variants.

You can use existing answers from the flow to template the API lookup URL with the standard syntax. The API lookup will not be dispatched unless all of the templated variables are defined, unless the variable is made optional (see below).

For more complex processing of results, you can write a mapping function using javascript. The editor here uses the same calculated answer's .

Variable type sets the expected that we are expecting from the response: string, number, or boolean. This needs to be properly defined for the API lookup to return successfully.

You can create to fine-tune when the API lookup should be dispatched.

This should be enabled if you'd like to wait until the API variable has completed the network call and any API variable functions have resolved. This is especially useful if the next step requires the return of the API for conditional logic or .

You can use the condition operator on a group, step, or question to affect the logic of a flow based on a failed answer, for example to put up a custom error message, or provide the responder an alternative way forward.

In flows, credentials are passed along with every request. This allows the use of cookies to authenticate requests to your own APIs.

๐Ÿ—๏ธ
Custom domains
templating
getter function body
variable templating
authenticated
select choices from an API
condition
al logic
templated
answers and analytics integrations
Calculated answer
Cross-Origin Resource Sharing
Calculate on submit
variants
answer
Had a loading error
data type
You can find your Client ID here, among other places.
Creating a dynamic URL for a GET request
logic conditions