Querying JSON Based APIs
GlobalForms can integrate with many different applications because of its capability to interact with web based APIs. In this example, we connect to a API to return the user's IP address and the City, State and Zip associated with that IP Address.Â
To build this yourself, construct a form with 4 Text Controls as follows:
Label Name | API Name |
---|---|
IP Address | IpAddress |
City | City |
State | State |
Zip | Zip |
Open the properties of your IP Address field, then click the Data tab. Select Custom Default value and paste the following code in, save your changes and test your form.
Pull IP Info From the JSON API
// Run if the field is empty if (!data.IpAddress) { console.log("Making HTTP Request"); data.requestInProgress = 'true'; // Here is the URL of the API We Are Pulling Formio.makeStaticRequest('https://ipinfo.io/json', 'GET', null, null).then(function (result) { // if the result exists if(result) { // Echo Setting Value to Console console.log("Setting Value"); // Here we set the value of IpAddress equal to the key in the JSON, IP data.IpAddress = result.ip; data.City = result.city; data.State = result.region; data.Zip = result.postal; } }) }
If you are unsure of the values that result may contain for you to query, try querying the result directly in the web browser.