Documentation

Your guide to everything Workflow.

Taking advantage of web APIs

You can take your workflows to a whole new level by taking advantage of the power of web APIs.

While most Workflow actions fill in the gaps between apps on your phone, sometimes you’ll find a gap between one of your apps and the web service that powers that app.

Perhaps an app doesn’t show you all the data you’re looking for, so you want to retrieve and work with the raw data yourself. Or maybe you want to automate the saving or posting of information to a service. Perhaps a service doesn’t offer a mobile app but does offer an API you can use.

For all of these situations (and many more), you can use Workflow to perform an API request.

What’s an API?

The term API stands for application programming interface. APIs are used to pass data back and forth in a formalized way. Many services offer public APIs that allow anyone to send and receive content from the service.

While APIs are a wide and general topic, the APIs we’re talking about with regards to Workflow are web APIs: ones that work over the Internet. On the web, you send a “request” to an API to get and post information.

All of your favorite apps that connect to the Internet are powered by APIs. For example, your favorite social media apps use APIs to let you view and publish posts from their mobile apps. When you refresh the feed, the app makes an API request to fetch all of the posts. When you “like” a post, the app makes an API request to post that data.

With the ability to make API requests in Workflow, you can go beyond the data locally available on your device and make workflows that interact with any web service that has a public API. You could build custom workflows to grab a bunch of data and display it however you want, or even send data back into the API and update the web service – if an API can do it, you can do it using Workflow.

To help you figure out how to harness this power in your workflows, we’ll walk through an example of building a Workflow that shows us the weather forecast using the Dark Sky API.

Download the example workflow and follow along as we go.

Signing up for the API

Most services will require you to sign up for their API, after which you will be assigned a “secret key” that grants you access. This key is included as part of the API request, letting the service know who’s making the API request – this key is unique to you and should not be shared with anyone else.

You can sign up for a Dark Sky account here.

Once you have your secret key, you’re ready to make your first API request.

Making your first API request

Making your first API request is super simple and takes only two steps in Workflow. First we need to create the URL that points at the API “endpoint” that we want to talk to, and then we can pass that URL to the Get Contents of URL action, which will make the API request when the workflow is run.

Building the request in URL

Dark Sky’s Forecast endpoint requires a URL request to be formatted as such:

https://api.darksky.net/forecast/[YOUR_SECRET_KEY]/[LAT],[LONG]

...with the text in brackets filled out with an API key and the location you want forecast data for.

In our example, place your API key from Dark Sky in the first Text action, which fills into the URL action using a variable. The LAT and LONG are already set to 37.8267 and -122.4233 are just the coordinates for Alcatraz Island in San Francisco, but you can change it to wherever you’d like. Try using Get Current Location and placing it as Magic Variable set to Latitude and Longitude in the URL to get local weather data whenever you run the workflow.

Performing the request with Get Contents of URL

When you run the workflow, the URL gets passed into Get Contents of URL, which actually performs the API request. Once Get Contents of URL is set to Advanced, you’ll see an option for the types of API request you can make – GET, which lets you retrieve data from an API to read; POST, which lets you create new data; PUT and PATCH which let you update data by replacing it or modifying it, respectively; and DELETE which lets you remove an object specified in the URL request.

In this example, we’ll be performing a GET request to retrieve data from the Dark Sky API.

Once Get Contents of URL is switched to POST, PUT, or PATCH, a new parameter will be added called Request Body that lets you send JSON, a Form, or a File to the API as part of your request. This lets you enter new data manually or using variables so can send it to the API for creating, replacing, or modifying an entry.

Now that URL has our request and Get Contents of URL is set up to GET data, you’re ready to make the API request! Tap the run button to test out the workflow – we’ve placed a Quick Look action in the flow so you can preview what data the API returns.

But in the meantime, congratulations! You’ve just made your first API request using Workflow.

Working with JSON

Looking at the data, you’ll notice that the API returns a lot of strangely formatted text. But if you look closely, you might notice that there is actual weather forecast information in there.

This weather data is encoded in what’s called JSON, which stands for JavaScript Object Notation. JSON is a popular data-interchange format used by APIs, mostly because its designed to be easy for machines to parse and generate, while still being easy enough for humans to read and write.

JSON lets you build structures around your information so that you can bundle lots of data together in one blob of text and send it along to another service. All the data values are given names, which are referred to as “keys”, then combined with special characters like colons (:) and curly braces ({ and }) to form data objects. Then, the machine on the other side of the request looks in between the special characters for the keys you’ve requested and breaks down the data back into actual values.

In JSON, your values are structured into two data objects: dictionaries and lists.

A dictionary is a collection of values that each have a unique key, together called key/value pairs. In JSON, they look like {key1: value1, key2: value2, key3: value3} (and so forth).

A list is simply an ordered collection of values. In JSON, they look like [value1, value2, value3] and so forth.

In both cases, the values can be set as text, numbers, booleans (true or false), dictionaries, and lists.

You’ll notice its possible to have a dictionary within a dictionary, or a list within a dictionary, or lists of dictionaries, or lists of lists – JSON lets you nest these two structures however you want. This allows you to model almost any structure of data, simple or complex, making JSON a powerful yet simple way to organize values as data objects.

For example, you can represent a person using a dictionary like:

{"first_name: "John", "last_name": "Appleseed", "age": 9}

Or, if you want a list of people, you can put the people dictionaries in a list like:

[{"first_name: "John", "last_name": "Appleseed", "age": 9},
 {"first_name: "Kate", "last_name": "Bell", "age": 10},
 {"first_name: "Anna", "last_name": "Haro", "age": 11}]

Note

If you would like to read more about the semantics of JSON, their official website is a great resource.

Parsing JSON from an API request

Looking at the Dark Sky API response, you can see that there’s a lot of data stored in the JSON. It’s not exactly easy to read at first, but over time you’ll start to recognize the data structures in JSON data like this and how to identify dictionaries, lists, keys and values. Often, developers will include a nicely-formatted version of the JSON data their API will return, so look for that in the documentation. Plus, it’s help to check your work using services like www.jsoneditoronline.org.

You’ll notice that the top-level object is a dictionary with the keys latitude, longitude, timezone, offset, currently, minutely, hourly, daily, and flag. Some of these such as latitude and timezone simply have a number or string value, but others such as daily have a dictionary value.

And that daily dictionary has some keys whose values are simple strings like summary with Mostly cloudy until tomorrow afternoon. but others like data are a list containing a forecast (represented by a dictionary) for each hour.

Handling dictionaries using Get Dictionary Value

JSON objects can sometimes get quite large and complex, but Workflow provides all the tools necessary for working with them.

To get the value for a particular key in a dictionary, you can use Get Dictionary Value and specify the name of the key. Since we want the daily forecast, we place Get Dictionary Value and set it to daily.

Looking at the dictionary of Daily, if we wanted to get the weather summary, we could use Get Dictionary Value again with summary.

However, we're instead going to extract the detailed forecast for each day, which is stored within daily as a dictionary called data instead of.

You’ll notice that data dictionary is actually a list of dictionaries, represented at the start by the [ in the JSON. Looking at the output of the Get Dictionary Value action in this example screenshot, you can see it outputs a list of 8 items shown by the page dots in the example screenshot. This represents the forecast data for each of the days requested from the API, which returns today and the next 7 days that becomes a list of 8 dictionaries of data.

But how do you work with multiple items in a dictionary? That’s where Repeat with Each comes in handy.

Handling lists using Repeat with Each

Repeat with Each allows a workflow to act on every item in a list, one after another. If you need a refresher on how to use the Repeat with Each action, you can refer to Using Repeat loops.

In order to work with our set of 8 days of data, you'll have to pass the output into Repeat With Each and then set up actions within each loop to retrieve one day's data at a time. Since we're looking for the average of each day's highs and lows, we'll move into the Repeat Loop and use a List set with two Repeat Item variables, one that's set to get the maximum temperature and another to grab the minimum temperature of each day.

Then, we use a Calculate Statistics action to average the two new values, and use Round Number to make the value a nice and readable version of average temperature for the day.

To make sure our raw data values are useful once they're passed out of the repeat loop, we'll extract the day of the week in order to use in our alert. With another Repeat Item variable set to the time key, we can extract a timevalue from the API and use Adjust Date to calculate the correct date from the timevalue (see the note below). We'll place the variables for the day of the week (extracted from Adjust Date) and average temperature (extracted from Round Number) into a Text action, so that our final output of each loop will be a line of text with our newly formatted data.

Once the workflow is run and reaches the Repeat with Each action, it will loop through each day's dictionary of data, perform the calculations, and then pass it the the End Repeat action. After all 8 repeats, all of the numbers are grouped together and pass out of the End Repeat action, available to use as input into another action or retrievable as a Repeat Results variable.

Show it as an alert

Now that we've repeated through all of the dictionaries, retrieved the day of week and average temperature for each, we'll display it to review using a Show Alert action. We simply add a custom title, place the Repeat Results variable as the body of the message, and we're good to go!

Once the workflow is run, it will call the API, repeat through all of the data, and pop up with your custom weather data in an alert!

Congratulations, you've made a full API request in Workflow.

Further exploration

Now that you’ve learned the basics of APIs and JSON using Dark Sky’s API as an example, it’s time to explore and see what other APIs you might be able to take advantage of.

There’s a whole world of APIs connecting services that you already use every day – just look for their API documentation, get an API key, and see what you can do with the almost infinite amount of data that you can bring into your own workflow.


Since APIs are such a huge topic, we've added some additional notes below for reference:

Some API limitations in Workflow

OAuth

We don’t currently have support for OAuth 2, a system of authentication that requires a user to manually enter their username and password into a login page.

Various endpoints

Often APIs have a variety of endpoints that you can use to request different types of data. Working with some APIs may require a series of API calls, at first to retrieve existing data to let you see what’s currently there and then another again later to add, update, or delete more data.

Rate Limiting

Many APIs have limitations at how often you make requests, aimed at limiting abuse of their service if someone makes thousands or millions of requests programmatically. Sometimes they are limited by hour, day, or month, or may require you to pay for the service after reaching a certain amount.

However, since you are creating a custom API key for your own use within Workflow, you likely won’t find yourself hitting the usage limits. You may come across this if you use Repeat actions to make a large number of requests in a short period of time - if that occurs, you may need to wait until your service is restored and/or batch your processes to only perform a limited amount of operations at a time.

Handling timestamps using Format Date

You might have noticed that the time for each forecast in the API response is just a large number that doesn’t particularly look like a date. This is because the time is formatted as what’s called Unix time (or Epoch time), which represents the time as the number of seconds since 00:00:00 UTC January 1, 1970.

This time is used a standard for all computers to use as a way measure time from the same spot, which is the start date of Universal Coordinated Time (UTC) and is also considered the birthday of the Unix operating system. In workflow, we can convert from Unix time to a more human-readable time format by using the Date, Adjust Date, and Format Date actions.

The Date action is set to 00:00:00 UTC Jan 1, 1970. Then, we add the Unix Time variable to the UTC date to get the adjusted date.Then, we can use Format Date to get rid of the time component since they are all 00:00:00.

Note

Other APIs might use other time formats such as ISO 8601. To read more about date format patterns, please refer to Understanding date and time formatting.

Using Dictionaries in your workflows

Outside of working with APIs, dictionaries can also simply be a useful way to work with structured data in your workflows. If you want to create a dictionary manually, you can enter text, numbers, values, dictionaries, or lists into the Dictionary action and use it in your workflows. Or, if you have a dictionary stored in a group of text, you can use Get Dictionary from Input to extract only the data object. And, if you want to later add new data into the object, you can use Set Dictionary Value on the output of another action.

You might just want to create a JSON dictionary without coding it manually, so you enter all of the values into a Dictionary action and copy the results. Or, you might use the Dictionary magic variable extract a set of values repeatedly throughout a workflow. Or, you might use a dictionary to make a rich display of data in Choose from List, which show the keys as menu options and their values as a previews; then, when you choose a key, the action will pass the corresponding value into the next action.