Querying JSON Based APIs

Forms can call web APIs that return JSON and use the results to fill in fields. For example, look up a ZIP code to fill in the city and state, or load a value from another business system.

Two ways to call an API

Method

Use it when

Select component with a URL data source

The API returns a list of options. No code is needed. See Select.

JavaScript in a component

You need to fill in several fields from one response. See the example below.

Before you begin: allow the API

GlobalForms only lets forms connect to approved sites. Add the API's address to connect-src in the Content Security Policy, then restart the GlobalForms service. See Security Headers.

The API must also allow requests from your GlobalForms address (CORS). Public APIs usually do; for your own APIs, ask the API's owner.

Example: fill in fields from an API response

This example calls an API from a button and fills in three fields. Create Text Fields with the property names city, state and zip, and a Button with Action set to Custom. In the button's Button Custom Logic, enter:

JavaScript
fetch('https://api.example.com/location')
  .then(function (response) { return response.json(); })
  .then(function (result) {
    data.city = result.city;
    data.state = result.region;
    data.zip = result.postal;
  })
  .catch(function (error) {
    console.log('The request failed', error);
  });

Replace the address and the property names (result.city and so on) with those of your API. To see what an API returns, open its address in a browser.

Use fetch, as above, for outside sites. The Formio.makeStaticRequest function adds the user's GlobalForms sign-in token to every request, so it would send that token to the other site. Use Formio.makeStaticRequest only for requests to GlobalForms itself.

Things to consider

  • Calls run in the user's browser, so anything the API returns can be seen by the user. Don't call APIs that return data the user shouldn't see.

  • Don't put API keys or passwords in form JavaScript; anyone who opens the form can read them. To use a protected data source, publish it through a GlobalForms SQL lookup route or your own server.

  • Some public services collect information about callers, such as IP addresses. Check the service's terms and your privacy requirements.