Full Stack Web Developer (Q1-Q2 2021)

Estimating read time ...
Edited 7th November 2021

Postman, APIs and Ajax

From the last section you would have seen the task is now to work with APIs and to integrate the OpenWeather API into your site, providing the current weather for a predefined location. To complete this task will require you to first understand APIs, how they work, how we can perform API calls and leveraging the Postman tool. This section is intended to cover all these processes.

There are actually multiple ways we can perform API calls, but to keep things simple we’ll be using JS/jQuery (client-side) and Postman in this section.

1. What are APIs?

The term is an acronym for Application Programming Interface (API), which is a computing method of communication between one or more applications. An API allows one site or application to communicate to another, enabling the ability to transfer data. When we make an API request from one site to another, this is referred to as an API call. The data which is transferred will be dependent on the capabilities of the API we utilise.

There are numerous APIs available on the web publicly and some which are private. We can also develop our own APIs for ourselves or other developers to utilise. Each API is unique and they provide various capabilities, we’ll work with OpenWeather today for gaining weather information and next week SendGrid for delivering emails. The capabilities of integrating with APIs are endless, we can geolocate IP addresses, perform lookups on car registrations and so on.

As each API is unique, each provider will have their own specific requirements to connect and retrieve the desired result (e.g. may require additional parameters, specific HTTP method, Oauth authentication and etc.). In addition to the connection and processing, each provider will also utilise varying standards; therefore to integrate we must read and familiarise ourselves with their documentation. Reading documentation when integrating with APIs are essential and an API with no documentation is almost completely worthless. (The documentation for some APIs will be better than others, and vice versa some will be below average standard.)

2. Understanding the JSON Syntax

Most APIs return data in either a JSON or XML format. XML was the standard from the 90’s to the mid/late 2000’s, until we shifted towards using JSON. Not all API providers however transitioned, and some APIs still utilise the XML format (especially legacy applications, most new applications will use JSON).

We will not be covering the XML API payload, although there is no learning curve to picking this up and it’s relatively straight-forward. We’ll be focusing instead on the current standard, JSON.

JSON, an acronym for JavaScript Object Notation is a format defined by JS. It’s significantly more lightweight in comparison to XML, meaning we can transport data faster and most programming languages (including PHP) provide the ability to parse JSON natively.

Here’s an example of data in the JSON format:

{ name: "John", age: 31, city: "New York" }

The JSON object starts with an opening brace and ends with a closing brace, in between the braces are key-value pairs (e.g. name => John, age => 31 and etc.). We can have an infinite amount of key-value pairs.

You’ll see that the key is declared first followed by a colon, then in quotation marks the value. When a value is defined inside quotation marks, this denotes that this is a string (i.e. text). You’ll notice that the ‘age’ value is not enclosed with quotation marks, this is because the value is an integer and not a string.

We can also provide nested data inside JSON (i.e. JSON inside JSON), for example:

{ name: "John", age: 31, address: { street: "2304 Oak Street", city: "Old Forge", state: "New York", zip: 13420 } }

Here you can see we’ve removed the city key-value pair and instead replaced it with the address key, where the value is a nested object holding more key-value pairs. We can also have an infinite amount of nested objects, but keeping it to a minimal is preferred.

And in summary, that’s all there is to the JSON syntax. It’s not overly complicated.

3. HTTP Methods

Last week when we created our HTML contact form which we processed using PHP, we performed POST and GET HTTP methods. When we submitted our form, we performed a POST with the form’s data (i.e. the input fields) and when we redirected the user back to the form on a successful submission we performed a GET to retrieve the parameters from the URL.

They are two of the most popular HTTP methods. Every time we visit a website, our web browser performs these POST/GET calls behind the scenes to request data from a server to then render on your web browser/device screen. Our browser also sends other data across, such as (but not limited to) the user-agent which includes the device we’re using, the browser, OS version and etc.

When working with APIs the final product we produce doesn’t request data using a web browser, instead we perform the calls programmatically which is why we only need a basic understanding of HTTP methods to get us started. Along with POST and GET, there are other methods such as PUT, PATCH, DELETE and etc. If you want more information on HTTP methods, please see the w3schools article.

4. Familiarising Postman

Using Postman is one of the ways we can perform API calls, however any calls performed in Postman are purely for development purposes and we must ultimately program the request into a programming language for it to be automated. Most high-level programming languages provide the capability to perform API calls, including but not limited to Java, Python, JS, PHP, C/C++ and etc. We use Postman for testing the APIs before we program them into the programming language of our choice.

To get started with using Postman, please open the application. You may be asked to register but you should be able to skip this (it may be a small link at the bottom of the app window); registering allows you to share your Postman collection and also keep all your work synced across multiple devices. So you may optionally register if you wish.

  • Upon opening the app, you’ll have your workspace; you can have multiple workspaces but for now one will suffice.
  • Workspaces are effectively equivalent to having multiple browser windows open. Inside your workspace you can have multiple tabs open; this is similar to having multiple browser tabs open connected to different sites. The tabs in Postman will allow you to be connected to multiple APIs.
  • Under the tab, you’ll have your address bar. On the left is the HTTP method; clicking it will reveal a drop-down allowing you to change the HTTP method to POST, PATCH etc. To the right end, you’ll have the ‘Send’ button to perform the API call. (Keep the HTTP method on GET for now.)
  • Under the address bar, you’ll have more tabs with a space for options: "Params," "Headers," "Body" and etc. For now Params, Headers and Body are the ones to focus on.
    • Params is short for parameters. This enables us to add parameters in the request URL, similar to how we did last week with the contact form.
    • Headers are not important to us now, but they include additional data we want to pass to the server processing the API request.
    • Body is the data we want to send inside our API request. This is useful in POST, PATCH, PUT and other HTTP methods, as we pass in data using a body (i.e. the payload). The data we pass in will generally be form-data (key-value pairs) or raw (JSON). The body is less useful in the GET method, as we can pass data using parameters with GET.
  • Under the tabs with configurable options is the ‘response’ section. After we perform an API call (i.e. once we click ‘Send’), the response we receive will be returned here. Depending on the API, this could a JSON or XML response. HTML (or any other format) can also be returned, but we are not expecting these with the API’s we’re working with.
  • Finally on the left-hand side bar of Postman you’ll have more tabs: History, Collections, APIs. (We can ignore the APIs tab, as we won’t be using this.)
    • History as the name implies will keep a history of all your API calls performed.
    • Collections contain all your saved API requests; collections are effectively similar to folders and you can save your API requests inside a collection. Usually I create a collection for every different project I work on, so that my saved API requests are not mixed between different sites/applications.

5. Making an OpenWeather Call using Postman

After creating an OpenWeather account, please see the 'Current weather data' section for a documentation on how to use their API. (As previously mentioned, all APIs are unique and we must conform to their documentation to utilise them.)

In Postman, ensure the HTTP method is set to ‘GET’ and in the address bar enter (taken from the API documentation):

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

Once you enter that into your address bar, you’ll see Postman will parse the URL and auto-populate the ‘Params’ tab with the key-value pairs. You can edit the values inside the Postman query parameters and the URL will update appropriately.

If you ‘Send’ the API response now (give it a try), you’ll get a HTTP 401 response. A HTTP 401 response is unauthorised; this is because we have not defined our API key. (HTTP 401 is a status code, similar to the infamous 404 amongst others, such as 500. For more details on status codes and what each one means, please see the Wikipedia article.)

In Postman, replace the {API key} value with the API key you’ve got from OpenWeather. You should have got an email after registering with your key, which is a string consisting of mixed letters and numbers.

Once you’ve entered your API key into Postman, ‘Send’ the API call again. If successful, you’ll now receive a 404 because the city could not be found. Replace the city name with Lancashire and try sending again. You should now see some data being returned. Analyse the data and familiarise yourself with the response, as we will be making use of some of the data in our site (we don’t need everything it has returned).

You’ll notice that we only performed a GET call for OpenWeather, we didn’t have to use any of the other HTTP methods. This is primarily due to the API call we performed being simple in nature and not too complicated. Other APIs do make use of all other methods (GET and POST are still the most used).

6. Ajax via jQuery

Now that we’ve performed the API calls using Postman, we can confirm that we are receiving the expected behaviour and the API is working as expected. We can now move onto rebuilding the Postman API call into programming code. Postman is a great way to debug code, if it works in Postman but not in your code, this signifies that there is something wrong with the code, not the API.

To perform API calls programmatically, today we’re only going to focus on JS via jQuery for simplicity (we’ll move onto performing API calls with PHP another time). We can perform calls using vanilla Javascript, however the jQuery library simplifies this for us drastically by providing us the Ajax methods; therefore today we’ll be using jQuery Ajax.

In your JS code (which should have the jQuery library loaded from the previous weeks), we can simply add the following code:

$.ajax({ url: "https://example.com/index.html", success: function (data) { // Your code here when a response is provided. console.log(data); // The data variable holds your response. }, });

You’ll need to replace the URL value to an appropriate OpenWeather URL. Inside your success function, you can perform your logic to display the appropriate weather details on your site. Using jQuery again we can do something similar to what we did in the Rock, Paper, Scissors game, e.g.:

$(‘.weather’).html(‘<p>Hello World!</p>’);

The above code would print ‘Hello World!’ inside any element with the ‘weather’ class (replacing any existing content), e.g.:

<div class="weather">Fetching …</div>

Instead of passing in ‘Hello World!’, you should instead cherry-pick the appropriate data to return inside your ajax success function from the data variable. Remember, as the data variable holds the weather data (if the response is a success).

Author(s)

Arif Ullah

Developer & CEO