Work with REST APIs – Take Control of Shortcuts

Work with REST APIs

Thankfully for us, most developers have quickly caught onto the power that is Shortcuts. But there are some web services for which developers haven’t (yet) added Shortcuts support, there is no app, or that enable you to do more by working directly with the service through its REST API. An API (Application Programming Interface) is a way we can talk to (web) applications and get information or send them commands, and a REST (Representational state transfer) API is a common, standardized format for web services. This means that with the right skills and actions, we can enhance Shortcuts ourselves.

An Introduction to API Calls with Shortcuts

We talk to these APIs primarily using one action, Get Contents of URL. This action does let us get the content of a regular webpage, but it also allows us to make requests with specific parameters (options we send to the server), authentication tokens (also known as API keys) to prove who we are, and different kinds of requests.

Make the Request

In there are five kinds of calls you can make to a URL for an API request:

  • GET: This kind of request is used to look things up.

  • POST: This request can create new items, or replace content in them—if you use this for updates, then in many cases it will delete any data you do not send to the API again. (For example, if you get data that has a title, and content, and an author, but only send author back, then the title and content will be deleted.)

  • PUT: Use this to update a resource and send all the fields.

  • PATCH: You can use this to update an item without sending all the data again.

  • DELETE: As the name implies, this deletes something—you must specify what will be deleted for this to work.

Not every API uses these actions in the same way (whether or not it is correct to do so), so the answer to “Which HTTP method do I use?” is unfortunately “Read the documentation.” To make this easier, I’ve chosen three different APIs below and will walk you through each one.

Use Authentication

Lots of APIs need you to verify who you are. In some cases this is because the provider wants to charge you, or because you want to access data which is not available to everyone. There are two common methods to do this:

  • Specify an API key in the URL: For example, the URL https://api.example.com/dictionary/aardvark could call a dictionary API, give it your key, and request a definition for the word “aardvark”.

  • Send an Authorization Header: See Figure 58. Some keys must be specified as Bearer [key] or Basic [key]; this is dependent on the type of authorization used, and should be clearly detailed in any REST API documentation.

Figure 58: Get Contents of URL with an Authorization Header.

Work with the Result

In general we get two formats of data back from an API request, JSON or XML. JSON stands for JavaScript Object Notation, and is a data format with keys and values. It works like a dictionary: you look up Aardvark (the key) and get “The aardvark is a medium-sized, burrowing, nocturnal mammal native to Africa.” (the value). XML is another format that supports keys and values, and allows you to add extra properties.

Here is some sample XML Data:

<step number="3">Connect A to B.</step>

Here is an equivalent in JSON format:

{ "steps":{ “3”: "Connect A to B." } }

The advantage of XML is that you can define the number of the step in the step property. With JSON, you have to define steps and then give it a series of values, but this also means you can easily get all the steps in one go.

XML can be more complex, and for that reason I focus on JSON data here. (You may want to review an introduction to JSON to learn more, if you are not already familiar with it.)

Shortcuts can use JSON as a dictionary with no extra work necessary, but with XML we must use the action Get Dictionary from Input. It coerces the data into the correct format for me and saves a lot of taps later, as I don’t need to convert the data to a dictionary every time I want to access it.

To see more on working with dictionaries, reference the Lists, Menus, and Dictionaries section.

Send Data Back to an API

You can send data back to the API with the same Get Contents of URL action, and change the Method to POST, PATCH or PUT—depending on what action it is you want to do, and which API you are working with.

Once the Method is set to something other than GET, a new section appears at the bottom of the action. This is the Request Body action, and we can use it to send JSON, Form (encoded), or File data. JSON works the same way as a dictionary action, Form lets you add text or file fields and specify the name of each, and File lets you choose a file to upload. In my experience, the majority of the time you will find JSON to be the format you need to use.

As the best way to understand all of this is to actually play with it, I’ve selected a few APIs to model for you here. This covers a variety of use cases, and will hopefully give you a few ideas to play with yourself.

Zapier

Zapier is a web automation platform that integrates with hundreds of services from BaseCamp to Slack, FreshBooks, and even Discourse. You can use a webhook, Zapier’s term for an API call (GET, POST, PATCH, etc.) as a trigger for your Zapier zap, and then make this call with a shortcut. This is a good workaround for APIs that require authentication not possible through Shortcuts, closed APIs, or even things which would be too time consuming to build in Shortcuts itself. For example, if I want to create a Message in Basecamp as part of a shortcut, I can use a webhook to POST to Zapier, and when Zapier receives my POST, it can send the right data to Basecamp for me. You can also use this to replace things you could do in Shortcuts, but don’t need to interact with. Zapier runs in the cloud so you can use your device for anything you like while it does the magic.

Airtable

Airtable is a cross between a spreadsheet and a database. It’s user-friendly, but also extremely powerful. It is also an ideal tool for automation as you can use it for everything from project management software to an inventory tracker or even a recipe manager. Airtable creates documentation for every one of your bases, so it should be easier to understand what you need to send it and how.

I frequently create Airtable records as part of a shortcut—for example when I have an idea for an article to write—as well as creating a draft for it in Drafts. I also save it to Airtable so I can keep track of the status. From Airtable I can then go back to the Draft using the magic of URL schemes (I talked about these in the section on Actions). I also get Airtable records as a starting point for several shortcuts. For video production, I can get all the records where I need to do something for setup, such as create a MindNode document (a great app I use to mind map a lot of projects), and work through each of them to do those actions before I update the record at the end.

Here’s an example with Airtable’s template Gift Ideas Tracker base. Check the documentation for the exact URLs you need to call, but here’s how to set this up:

  1. Sign up for Airtable.

  2. Open the Gift Ideas Tracker and tap “Use template,” then import it to your bases.

  3. Go to https://airtable.com/api and find the Gift Ideas Tracker in the list, open it.

  4. Open the Authentication link, and copy the URL after curl—it should look something like this: https://api.airtable.com/v0/app[base_id]/Gift%20Ideas.

  5. Create a new shortcut.

  6. Add an Ask for Input action.

    Change the Question to Item.

  7. Add another Ask for Input action.

    Change the Question to Notes.

  8. Add a URL action.

    Paste the URL from step 4 into it.

  9. Add a Get Contents of URL action.

    Tap Show More and change the Method to Post.

  10. Tap Headers in the Get Contents of URL action and then tap Add a New Header.

    Set the key to Authorization, and the value to Bearer [Your API Key] (there’s a checkbox on the Airtable API page to show your API key).

  11. Still in the Get Contents of URL action, under Request Body, Add a new Field, using the Format Dictionary.

    Set the key to fields (lowercase—this is important!), and tap 0 items. Add a new item, and select the Text type. Set the key to Item and the value to a magic variable, the Provided Output from step 6. (Don’t panic; after you select the variable, you are not in the fields anymore.)

    Add another new item, also of type Text. Set the key to Notes and again set the value to a magic variable, the Provided Output from step 7.

Now, run your shortcut! It should ask you for the item, and then notes, and then save everything to Airtable. If you don’t believe me, open the Gift Idea Tracker in Airtable and see!

Install Add Gift Idea To Airtable shortcut: https://alt.cc/shgi

Manage API Keys with Shortcuts

Now comes the time to get ahead of ourselves and prepare for the next chapter, Work with REST APIs. An API key needs to be available in multiple shortcuts, otherwise if/when you change it you will have a lot of work to do. For this to work, we need to be able to take multiple actions here:

  • Save a key

  • Copy a reference to a key

  • Update a key

  • Delete a key

Because we will want to do one of these commands at a time, and each command executes different actions, this is another perfect use case for a menu.

When you install the shortcut, you answer an import question, which replaces the content of the first Text action with the name of the folder you input. I renamed this to Folder Name and reference it in all of the Get File and Save File actions. Below this is a Create Folder action. After you run the script for the first time you can delete this—but Shortcuts will not overwrite the folder if the action remains.

The first menu option, Save, asks you for the key, defaulting to the clipboard, and then the name of the service. It saves the key in a file with the name of the service—so in a shortcut where you need the API key, you can run Get File and use a reference to the file.

The next menu option copies a reference to the key to our clipboard—a fancy way of saying the file path. It uses a trick to get all the files in the API key folder, Get File and give it just the name of the folder. With a Choose from List action we choose our file, construct the file patch in a text action and copy it to our clipboard.

Update key works similarly to Save a key, but instead of the step to enter a service name we replace it with the same Get File and Choose from List actions as in the Copy Reference. We can then use the name of the File result to set the name of the API key and in the Save File action we toggle the Overwrite If File Exists option on.

The final menu option, Delete Key, uses the same pairing Get File and Choose from List again, and we follow it with a Delete File action.

Shortcuts can and will delete one item without confirmation—though for Delete Files, Confirm Before Deleting defaults to on. Shortcuts always asks you to confirm the deletion of 10 or more files—three times (Figure 59).

Figure 59: Shortcuts alert to prompt before it deletes

You can work around the confirmation requirement and use a “Repeat With Each” action to delete items one at a time, but don’t forget to turn off Confirm Before Deleting!

Install Manage API Keys shortcut: https://alt.cc/shma