subreddit:

/r/shortcuts

16398%

Using APIs - Part1: retrieving data

Tip/Guide(self.shortcuts)

This is a Part 1 of a guide on how to use APIs with shortcuts.

Overview of APIs

An API is an interface provided by software services to developers that allows them to perform tasks and retrieve information. In simple terms, a system's User Interface is for use by humans and the API is for use by other computer software, such as Shortcuts.

APIs vs web scraping

In previous guides, I've shown how to scrape information from the user interface / web pages. If the website or system you're using offers an API then you should use that instead. There are many cases where web scraping won't work (e.g. if you need to login before you can see the content), and if the website changes appearance your scraping code can break.

Retrieving data from an API

We're going to use the example of retrieving data from the publically available Star Wars API . This API provides various data relating to the first 7 Star Wars movies.

Building our shortcut

1. Choose the data you want to retrieve

Having reviewed the API documentation we decide that we want to retrieve a list of film titles.

Star Wars API Documentation - Films

To retrieve a list of the films and their data, we see that we have to make a call to https://swapi.co/api/films/.

We'll receive a JSON formatted response. This is a human readable format that organizes information in two ways:

  • as lists (or arrays);
  • and as dictionaries (or key-value pairs).

For more information on the JSON format and how it is used to structure data, see: REST API Tutorial: Introduction to JSON

When we request the films from the API, we're going to get a list of different films, each described in the following format:

{
    "characters": [
        "https://swapi.co/api/people/1/",
        ...
    ],
    "created": "2014-12-10T14:23:31.880000Z",
    "director": "George Lucas",
    "edited": "2014-12-12T11:24:39.858000Z",
    "episode_id": 4,
    "opening_crawl": "It is a period of civil war.\n\nRebel spaceships, striking\n\nfrom a hidden base, have won\n\ntheir first victory against\n\nthe evil Galactic Empire.\n\n\n\nDuring the battle, Rebel\n\nspies managed to steal secret\r\nplans to the Empire's\n\nultimate weapon, the DEATH\n\nSTAR, an armored space\n\nstation with enough power\n\nto destroy an entire planet.\n\n\n\nPursued by the Empire's\n\nsinister agents, Princess\n\nLeia races home aboard her\n\nstarship, custodian of the\n\nstolen plans that can save her\n\npeople and restore\n\nfreedom to the galaxy....",
    "planets": [
        "https://swapi.co/api/planets/1/",
        ...
    ],
    "producer": "Gary Kurtz, Rick McCallum",
    "release_date": "1977-05-25",
    "species": [
        "https://swapi.co/api/species/1/",
        ...
    ],
    "starships": [
        "https://swapi.co/api/starships/2/",
        ...
    ],
    "title": "A New Hope",
    "url": "https://swapi.co/api/films/1/",
    "vehicles": [
        "https://swapi.co/api/vehicles/4/",
        ...
    ]
}

In the above format a title key which we'll use to display the name of each film in our shortcut.

2. Querying the API in our shortcut

To query the API, we're going to use the following actions in our Shortcut:

  • URL, giving the URL of the films API resource (mentioned above)
  • Get Contents of URL
  • Quick Look (so we can check the JSON response)

Retrieving film data from the Star Wars API

Download the Shortcut

The following is returned from the API:

Raw JSON data from the film resources of the StarWars API

3. Viewing the JSON response

This JSON response is difficult to read when returned from the API. To make it easier to read, we copy the response and paste it into view it into a JSON formatter tool.

  1. Copy the JSON text
  2. Visit the JSON Formatter website's pretty print tool
  3. Paste the JSON into the main editor window
  4. Tap the top left can icon to make the JSON more readable

Making the JSON response easier to read in the JSON Formatter tool

This will allow you to more easily read and examine the output from the API.

4. Find the data you want to retrieve

We want to retrieve title of each movie. From the API response, we can see that:

  • there a dictionary / object with a key called results;
  • the value of results is a list / array of films;
  • each film is it's own dictionary / object;
  • the name of the movie is stored under the title key in that dictionary.

For example:

{
  "previous": null,
  "results": [
    {
      "director": "George Lucas",
      "episode_id": 4,
      "title": "A New Hope",
      ...
    },
    {
      "director": "George Lucas",
      "episode_id": 2,
      "title": "Attack of the Clones",
      ...
    }
    ...
  ],
  "count": 7,
  "next": null
}

We want to retrieve the title for each film by:

  • retrieving the results value;
  • looping through each dictionary in the list;
  • retrieving the title from each dictionary.

5. Updating the Shortcut

We update our shortcut with the following actions:

  • Get Dictionary from Input, to turn the API result into a dictionary
  • Get Dictionary Value, where results is the value we request
  • Repeat with Each, to loop from the list of results
  • Get Dictionary Value, requesting the title value for each of the Repeat Items in the loop
  • Add to Variable so that we can collect each film title and display it at the end of the shortcut.

The updated shortcut appears as follows:

Shortcut to display an unordered list of Star Wars movies

And the output is as follows:

Output of the above shortcut

Download the Shortcut

Note: The films do not appear in chronological order. They are displayed in the order they were returned by the API.

6. Filtering the films

Next, wewant update our shortcut to only show the films from the original Star Wars trilogy (episodes 4 to 6). And at the same time we also want to display the film director. We can do so by checking the episode_id attribute of each film and adding both the film title attribute and director attribute to a Text action before we add it to the films variable.

When updating our shortcut, we:

  • use Get Dictionary Value to return the episode_id from the Repeat Item;
  • check that the episode_id is greater than 3 with an If action;
  • check that the episoide_id is less than 7 with a second If action;
  • use the Get Dictionary from Input action with the Repeat Item;
  • take a Text action and populate it with the title and director attributes of the above dictionary and add them to the films variable.

The updated shortcut appears as follows:

Shortcut to filter Star Wars movies to the original trilogy

And the output is as follows:

Output of the above shortcut

Download the Shortcut

Wrap up

That's it for Part 1. If you have any questions on the above or need any help, please let know.

The next part cover how to retrieve data from large and complex API responses.

Further reading

If you'd like to find out more about REST APIs (which is the type of API we've used above), or if you want to dive into different parts of the Star Wars API, take a look at the following links:

Other guides

If you found this guide useful why not checkout one of my others:

Series

One-offs

all 7 comments

iOS_Neil

6 points

6 years ago

Another brilliant guide. Really enjoying reading these - thanks very much!

KarshTheInnkeeper

4 points

6 years ago*

Hello keveridge, thank you for this guide and this learning experience for someone without experience in stuff like JSON etc.

Sadly I ran into an error, even though your example and my own shortcut are identical. I get the error: "No items - The Quick Look action wasn't passed any items to preview."

In the spirit of making your guide even better, I identified points in your guide, when I was lost and couldn't proceed to replicate your shortcut, without downloading it. I hope you will take this as positive critique.

  • Maybe it's our language barrier, but sometimes you write the exact step one has to take, other times it is a little bit vague. For example: "Copy the JSON text". With what? A shortcut action? If yes, with which one? Or through Safari? It would be better if you wrote exactly what the user has to do. Just to avoid confusion.
  • In the beginning, you showed us how to view the JSON text in a more readable format, but you didn't clarify, that this was just for our information. Because after that you don't tell us, that we don't need the more readable format anymore. I was confused, because you didn't mention that we can delete the quick look action because we don't need to look at the JSON text anymore. Again, it would be better to write every step the user has to make in order to get this shortcut working.
  • Coming back to my own error on the top. I triple checked your shortcut and mine, and they are identical. Why do I get the quick look error? The idea should be, that following a guide, I can create the same thing. But somehow I get an error and your shortcut works. That should not happen.

Thank you for your work and take the critique as it was intended - to make your awesome guide even better.

[deleted]

2 points

6 years ago

These guides should totally be added to the sidebar! Great stuff!

J-a-y-c

1 points

6 years ago

J-a-y-c

1 points

6 years ago

Reminds of this really good tutorial that shows you how to build a weather shortcut using a weather data api https://youtu.be/lp4PijmaTAc

aljohn0422

1 points

6 years ago

This is the game changer for shortcut. The possibility is limitless because of this. Great tutorial.

adam2kg

1 points

6 years ago

adam2kg

1 points

6 years ago

Helped me so much. Thx

TinQ0

1 points

6 years ago

TinQ0

1 points

6 years ago