How to read data from an external json api using javascript

i am really confused with this JSON API, please post some links that can help me.


Can you be more specific? Which API?

As @ksjazzguitar said the question is quite broad, so it’s hard to answer precisely to your needs.

Nonetheless I’ll try to give a “broad” example of how an API + API-request works.

Let’s start from the API

The simplest definition of an API is in my opinion:

In general terms, it is a set of clearly defined methods of communication between various software components

So it’s just a program that is instructed to respond in a certain way when asked in a specific way.
I’m gonna use as an API (it’s made specifically to test API requests)

We will focus on two GET request supported by the API that are:

GET	/posts
GET	/posts/1

This means that the folks over at has instructed their server that:

So this is what the API does, to a certain question (/posts or /posts/1) reply in a certain way.

The client request

Instead of JQuery’s getJson or Ajax request I am gonna use axios as an example because in my opinion is clearer in what it’s doing.
(You don’t need to know axios to understand this)

So now I want my webpage to be the one to “ask the question” and let the API provide the response.
Therefore I’ll proceed and in my webpage I’m gonna start by creating a GET request since as we saw, the API is instructed to respond to those requests.

// make a get request to the /posts page

Now we have made our request. Since we are expecting a response from the API (in this case we are expecting 100 posts to be send back) and presumably we want to do something with the data that we asked about we use a then() to wait for the response and perform our action:

// make a get request to the /posts page
 // we ad our then method. This means that once the response from the API arrives 
 //we will perform what we declare in the function
 .then(function (response) {
    //here you can do whatever you want with the data you have received.
   //in this case I will just console the response that the API sent

We want to access only one post? Simply change the GET request address that we perform:

// make a get request to  /posts/1
 .then(function (response) {
      // stuff we want to do

I created a fiddle to show you this functionality in action here:

Hope it helps :slight_smile:


I found this tutorial really helpful; it explains JSON and AJAX request in very clear way

1 Like