You walk into your local Coffee Shop, walk in the door and the cashier greets you. You're a regular there. You order your "regular" and the cashier seems to know what you mean by it. They make you a Super Large Frappuccino with Hazelnut drips and Whipped cream. You take it to your "regular" table and once you're done, you greet the cashier and staff goodbye and go on with your day.

Apart from the fact that you now know my regular coffee order, the entire process was eased up because of one tool that everyone in the coffee shop including you understood: Communication. Usually taken for granted, you can understand this entire course and everyone around you (or well, most of them) because of this nifty little tool, it could be the language you speak, the written message you pass around or just a head nod.

So far, we've been working with ourselves in isolation and it's time we venture out to the outside world. It will be scary at first, but as time passes by you'll get good with your communication as a developer.

The tool in our communication set is understanding what an API is.

API or Application Programmable Interface is a middleware for two or more applications on the web to talk to each other. This is the same as using a language to talk to another person. APIs take an input, process it and output the result, the same as asking the cashier for the regular order (the input), the cashier which clearly understands what you're talking about and processes your end output, or the coffee. There are a lot of things that goes into making a good API like writing great documentation which includes clear instructions on the kind of inputs the API takes, what it processes and what it doesn't, and how the structure of the end result would look like. There are a lot of things that go into making an API good, but for now let's focus on understanding and using APIs.

Just like real life languages with a lot of variations and branches, APIs come in two languages:

  • REST
  • SOAP

In today's chapter we will be talking about the REST API.

REST or REpresentational State Transfer is the more common API style used on the internet because of it's structure and ease of use. There are a lot of concepts about what REST API really is, but for now let's talk in plain english before we dive into techincal terms.

Let's see an API in action. For this we need two things:

  • Something to make the REST API calls and show their output.
  • A server that accepts and returns REST calls.

To run our REST API queries, we will be using Postman. Head over to their website, sign up for an account and download the program for your platform.

To see the API in action, we will be using Open Weather Map to get current weather of our location or any city. Head over to their website and signup for an account.

Now in Open Weather Map, head over to the API Section and you will be greeted with a page that shows you "Current and weather forecast weather data collection". We will be using the Current Weather Data collection. Open the API Doc and try not to panic.

First we need the API URL. In the By City Name section, you'll be greeted with 3 URLs:

  • api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key}

  • api.openweathermap.org/data/2.5/weather?q={city name},{state code}&appid={your api key}

  • api.openweathermap.org/data/2.5/weather?q={city name},{state code},{country code}&appid={your api key}

For a REST API, we usually first get hold of the URL. We will be using the first URL. Let's copy that and open Postman.

After logging in to Postman, you'll be greeted with the welcome screen. (You can click on settings > themes and switch to dark mode):

Click on New > Request and fill out the request name and description.

This is for your use and identification so the values here won't interfere with the end result. I am naming it Weather Data and creating a new collection called Open Stuff. You'll now be greeted with this screen:

In the request URL section, we first ensure the request is set to GET (we talk about this later in this chapter) and copy the first URL from Open Weather Data

api.openweathermap.org/data/2.5/weather?q={city name}&appid={your api key}

You'll notice Postman automatically updates the parameters. A REST API's URL takes in parameters as it's input strings. If this were an apex method, it would look something like this:

public static String weather(String q, String appId){
	String weather = getWeather(q);
	return weather;
}

For the q or city name parameter, write the city you want to get weather for. I'll go with Birmingham (UK)

Now we need to get our API key. This is the equivalent of a password and must be kept a secret because using this key your limits are calculated. Let's say if your API key were to leak, not only can anyone can now access data behind the API, all requests made are now counted towards your limits even if someone else did it. So let's keep it a secret. To get your API Key, sign in to Open Weather Map and head over to your API Keys in your dashboard. Give your API key a name and click on generate.

Copy your API key (I reset mine so it doesn't exist, please don't use this one) and update it in Postman. Now we have our city and API key ready, let's click on send! If you get the "Invalid API key" error, wait for 5 minutes as it takes a while for new API keys to work.

This response is in a JSON format. JSON or Java Script Object Notation, a language that stores data in an organised, key-value format (just like Maps in Apex). Let's break down this JSON and learn what it really is:

{
    "coord": {
        "lon": -86.8,
        "lat": 33.52
    },
    "weather": [
        {
            "id": 800,
            "main": "Clear",
            "description": "clear sky",
            "icon": "01d"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 301.55,
        "feels_like": 298.78,
        "temp_min": 299.26,
        "temp_max": 302.59,
        "pressure": 1020,
        "humidity": 35
    },
    "visibility": 16093,
    "wind": {
        "speed": 4.6,
        "deg": 20
    },
    "clouds": {
        "all": 1
    },
    "dt": 1590966265,
    "sys": {
        "type": 1,
        "id": 3436,
        "country": "US",
        "sunrise": 1590921512,
        "sunset": 1590972705
    },
    "timezone": -18000,
    "id": 4049979,
    "name": "Birmingham",
    "cod": 200
}

Open the documentation and head over to the "Parameter" section (if you click on the link it directly takes you there) where you have an example API and Parameters describing what each field means.

This is how a JSON File is structured:

  • Key Value pairs just like a Map in Apex, separated by ,.
    "timezone": -18000,
    "id": 4049979,
    "name": "Birmingham",
    "cod": 200
  • Objects are stored between { }
"main": {
        "temp": 301.55,
        "feels_like": 298.78,
        "temp_min": 299.26,
        "temp_max": 302.59,
        "pressure": 1020,
        "humidity": 35
    }
  • Arrays are stored between [ ]
 "weather": [
        {
            "id": 800,
            "main": "Clear",
            "description": "clear sky",
            "icon": "01d"
        }
    ]

Let's write a JSON File for a Contact with 3 Opportunities and associated to Account GenePoint:

{
	"Name": {
		"firstName": "John",
		"lastName": "Smith"
	},
	"Opportinity": [{
			"Name": "Opportunity Name",
			"Close Date": "03022020",
			"Amount": 2200
		},
		{
			"Name": "Opportunity 2 Name",
			"Close Date": "03122020",
			"Amount": 3000
		},
		{
			"Name": "Opportunity 3 Name",
			"Close Date": "12062020",
			"Amount": 800
		}
	],
	"Account": "GenePoint"
}

Let's break this down:

  • First we have the Name object with 2 key value pairs firstName and lastName.
  • We now have an Opportunity Array that holds values for 3 key value pairs Name, Close Date and Amount
  • We have a key value pair Account that holds the value GenePoint

Think of it this way:

  • Data is stored in key value pairs
  • If there's more than 1 key value pair for something, we define it as an object and store it between { }
  • If there are groups of information about a single object, but define different instances, we store it in an array between [ ]

Coming back to our Open Weather Data response, we can now understand the JSON, but in the case of Birmingham, notice how the JSON returned:

    "sys": {
        "type": 1,
        "id": 3436,
        "country": "US",
        "sunrise": 1590921512,
        "sunset": 1590972705
    },

"country": "US" means there exists a Birmingham in US, while we were looking for Birmingham in the UK! The people at Open Weather Data knew this would be an issue that's why they have additional URLs to access the same information:

  • api.openweathermap.org/data/2.5/weather?q={city name},{state code}&appid={your api key}

This let's us define the state and city name, reducing chance of errors. This is an example of good API design, equivalent to our "I'll have the regulars" coffee order.

Just like Apex has DML statements, REST has it's own version of DML Statements. Remember when we made a GET request in Postman to get information on the URL? That was the equivalent of running a [SELECT all_info FROM Current Weather Data WHERE City = 'Birmingham']. Here are some common DML statements used in REST API calls:

REST Call Apex / Description
GET [SELECT]
POST insert
PUT Roughly upsert. A Put call can create or replace information.
PATCH Used to edit minor details. Most similar to an update
DELETE delete

Summary

  • APIs are how applications over the internet interact with each other
  • REST and SOAP are two "languages" of API
  • REST is more commonly used because of ease of use and understanding
  • REST has it's own set of DML statements just like Apex
  • JSON is a format to store data in an organised way
Day 22: REST API Class and Making Snippets