Search results

Inspect the JSON from the response payload

Keep current with the latest trends in technical communication by subscribing to the I'd Rather Be Writing newsletter. 5,000+ subscribers

I'm giving an API documentation workshop in San Francisco, California, on November 19, 2019. Check it out on EventBrite and register today to receive a $100 early bird discount.

Seeing the response from curl or Postman is cool, but how do you make use of the JSON data? With most API documentation, you don’t need to show how to make use of JSON data. You assume that developers will use their front-end development skills to parse through the data and display it appropriately in their apps. However, to better understand how developers will access the data, we’ll go through a brief tutorial to display the REST response on a web page.

Activity 2e: Make an API request on a web page

For this activity, you’ll use JavaScript to display the API response on a web page. Specifically, you’ll use some auto-generated jQuery code from Postman to create the AJAX request. You’ll get the wind speed from the response and print it to the page.

  1. Open a text editor such as Sublime Text.
  2. Paste in the following code:

    <html>
       <meta charset="UTF-8">
       <head>
          <title>Sample page</title>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
          <script>
             var settings = {
             "async": true,
             "crossDomain": true,
             "url": "https://api.openweathermap.org/data/2.5/weather?zip=95050&units=imperial&appid=fd4698c940c6d1da602a70ac34f0b147",
             "method": "GET"
             }
    
             $.ajax(settings).done(function (response) {
                     console.log(response);
                     var content = response.wind.speed;
                     $("#windSpeed").append(content);
                   });
    
          </script>
       </head>
       <body>
          <h1>Sample Page</h1>
          wind speed: <span id="windSpeed"></span>
       </body>
    </html>
    

    This code is explained in more detail in a section below.

  3. Save the file as an HTML file named weather.html.
  4. Start Chrome and open the JavaScript Console by going to View > Developer > JavaScript Console.
  5. In Chrome, press Cmd/Ctrl + O and select your weather.html file.

    The weather response should be logged to the JavaScript Console (due to the console.log(response) code in the request). If you expand the object returned to the console, it will look as follows:

    JSON payload from weather API logged to console

    One of the properties in the response is wind.speed. The wind speed is shown on the page as well.

Step-by-step explanation

The above activity simply had you paste a chunk of prewritten code onto a web page, without much explanation. In this section, we’ll step through that code with details about how it was assembled. However, we won’t dive too deeply into JavaScript and jQuery here, as this is somewhat beyond the scope of the instruction.

To create the web page code from scratch:

  1. In a text editor (such as Sublime Text), create a new HTML file and paste in the following boilerplate template (which contains basic HTML tags and a reference to jQuery):

    <html>
    <meta charset="UTF-8">
      <head>
          <title>Sample page</title>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      </head>
    <body>
      <h2>Sample page</h2>
    
    </body>
    </html>
    

    jQuery is necessary because we’re using the ajax method to make the API request.

  2. Save your file (anywhere convenient) with a name such as weather.html.
  3. Open Postman and go to the Current weather data (weather) endpoint that you configured in an earlier activity (see Submit requests through Postman for more information).
  4. Click the Code link (below the Save button), and then select JavaScript > jQuery AJAX.

    JavaScript Ajax code snippet
    JavaScript Ajax code snippet

    The AJAX code looks as follows:

    var settings = {
      "async": true,
      "crossDomain": true,
      "url": "https://api.openweathermap.org/data/2.5/weather?zip=95050&units=imperial&appid=fd4698c940c6d1da602a70ac34f0b147",
      "method": "GET",
      "headers": {
        "User-Agent": "PostmanRuntime/7.15.2",
        "Accept": "*/*",
        "Cache-Control": "no-cache",
        "Postman-Token": "8a9aeae7-f063-42e8-b0e3-09d1a7069bd5,5468d865-c341-4596-9acc-faba0e0c0c7d",
        "Host": "api.openweathermap.org",
        "Accept-Encoding": "gzip, deflate",
        "Connection": "keep-alive",
        "cache-control": "no-cache"
      }
    }
    
    $.ajax(settings).done(function (response) {
      console.log(response);
    });
    
  5. Click Copy to Clipboard to copy the code sample.
  6. In your HTML file, insert the copied code inside a pair of <script></script> inside the header tags.
  7. In the jQuery code, remove the entire headers object from the Postman code:

    "headers": {
      "User-Agent": "PostmanRuntime/7.15.2",
      "Accept": "*/*",
      "Cache-Control": "no-cache",
      "Postman-Token": "8a9aeae7-f063-42e8-b0e3-09d1a7069bd5,5468d865-c341-4596-9acc-faba0e0c0c7d",
      "Host": "api.openweathermap.org",
      "Accept-Encoding": "gzip, deflate",
      "Connection": "keep-alive",
      "cache-control": "no-cache"
    }
    
  8. Remove the extra comma after "method": "GET" to keep the JSON valid.
  9. Below console.log(response); (but still inside the function’s closing brace });), create a variable called content and set it equal to response.wind.speed. Then use the jQuery append method to append content to an element called #windSpeed:

    $.ajax(settings).done(function (response) {
        console.log(response);
        var content = response.wind.speed;
        $("#windSpeed").append(content);
      });
    

    When ajax retrieves the response from the API, it assigns it to response. You can access the properties in the response using dot notation. The append method in jQuery allows you to append content to a particular element.

  10. Create an element on the page (below the h1 tags) with the id="windSpeed":

      <body>
         <h1>Sample Page</h1>
         wind speed: <span id="windSpeed"></span>
      </body>
    
  11. Save the file and open it in Chrome. Open the JS Console to view the object logged.

    You can view the file here: weather-plain.html.

The AJAX method from jQuery

In this section, I’ll explain a bit more about the ajax function you used earlier. This information probably isn’t essential for documenting REST APIs, but it’s good to understand. In the code, here’s the ajax script:

<script>
   var settings = {
     "async": true,
     "crossDomain": true,
     "url": "https://api.openweathermap.org/data/2.5/weather?zip=95050&appid=fd4698c940c6d1da602a70ac34f0b147&units=imperial",
     "method": "GET"
   }

   $.ajax(settings).done(function (response) {
     console.log(response);
   });
</script>

If you’re working with JavaScript and APIs, the ajax method from jQuery can be helpful with code samples. This ajax method takes one argument: settings.

$.ajax(settings)

The settings argument is an object that contains a variety of key-value pairs.

var settings = {
}

Each of the allowed key-value pairs is defined in jQuery’s ajax documentation.

Some important values are the url, which is the URI or endpoint you are submitting the request to. Another value is headers, which allows you to include custom headers in the request.

Look at the code sample you created. The settings variable is passed in as the argument to the ajax method. jQuery makes the request to the HTTP URL asynchronously, which means it won’t hang up your computer while you wait for the response. You can continue using your application while the request executes.

You get the response by calling the method done.

$.ajax(settings).done(function (response) {
})

In the earlier code sample, done contains an anonymous function (a function without a name) that executes when done is called. The response object from the ajax call is assigned to the done method’s argument, which in this case is response. (You can name the argument whatever you want.)

You can then access the values from the response object using object notation. In this example, the response is just logged to the console.

If you’re new to JavaScript, this is likely a bit fuzzy right now. If so, don’t worry — code becomes clearer the more you use it.

Notice how difficult it is to explain code? This is one of the challenges of developer documentation. Fortunately, you wouldn’t need to explain much from standard programming languages like JavaScript. But you might need to explain how to work with your API in different languages. I cover this topic in more depth in Code samples and tutorials.

Logging responses to the console

The line of code that logged the response to the console was simply this:

console.log(response);

Logging responses to the console can be a useful way to test whether an API response is working (it’s also helpful for debugging or troubleshooting your code). The console collapses each object inside an expandable section. You can inspect the payload in the console to see if contains the values you expect (without printing values to the page).

Inspect the payload

Inspect the payload by expanding each of the sections returned in the JSON console object. Based on the information here, what’s the forecast for today?

I realize the page is blank and unexciting. In the next section, Access and print a specific JSON value, we’ll pull out some values and print them to the page.

45% Complete

45/146 pages complete. Only 101 more pages to go.

Donate?

Want to buy me lunch? Click the Donate button below to donate any amount through Paypal.