Fetching and consuming from an API

What is an API

An API is an interface into a computer system—an application programming inter- face.

API gives us ability to interact with system without worry much about the implementation details

Like we said earlier an API aids us in interacting with an application.We can perform all the crud operations.For this to be possible an API must be well document, this entails how to send data and what type of data you will get back. We will use a dummy API end point JSONPlaceholder to fetch and display user details on a table.

Our front end will be a react application

Generating react application

1
$ npx create-react-app Blog

Delete the content of src directory like so:

1
$ rm -rf src/*

Let us create index.js and App.js inside.

src/index.js

1
2
3
4
5
6
7
import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';


ReactDOM.render(<App />, document.getElementById('root'));

src/App.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import React from 'react';
function App() {
  return (
    <div>
      <p> hello world</p>   
     </div>
  );
}

export default App;

Run either of these commands to start the server.

1
$ yarn start

or

1
$ npm start

Hello world should pop up on the

Understanding the documentation

For successful interaction of an API we must clearly read and understand it documentation on how it should be used. JSONplacehoder explains in details in with examples how to perform all the operations on their API here.We realize there are several resources which have relationships or associations.For instance user has many posts and post can have many comments and so on Since our interest is the user resource,let us investigate user further.From what is documented we see that maximum number of users are 10.And response which comesback when we try to get all users is like so:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[
[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  }, ...
]

We are only interested in user in name, email,phone number and website so that is what we will pick.

Using Fetch API

The Fetch API provides an interface for fetching resources (including across the network).In this case we are fetching data from JSONPlaceholder.

Let us create users component like so:

src/components/Users.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import React, { Component } from "react";

class Users extends Component {

  constructor(props) {
    super(props);
    this.state = {
      users: []    
    };
  }
}
export default Users;

Since we know from the documentation, when we fetch or get all users the response is inform of an array therefore we set initial state of our users to be an empty array.

Now let us try send our request and console log the response and see if it the actual thing we get.

src/components/Users.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  // truncated
  componentDidMount() {
  fetch("https://jsonplaceholder.typicode.com/users")
    .then(res => res.json())
    .then(json => console.log(json))
}
render(){
  return(
    <p>Just console logging our users</p>
  )
}
export default Users;

componentDidMount method is available after the component has mounted. That is after the HTML from render has finished loading. It is called once in the component life cycle and it signals that the component and all its sub-components have rendered properly.In our case after we make our api call and

Fetch api like said is use to make requests.What comes back(response) is known as the promise, we capture this promise using then

Now let us render this and view it from the browser.

src/App.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  import React from 'react';
  import Users from './Users'

  function App() {
    return (
      <div>
        <Users/>

      </div>
    );
  }
  export default App;

Visit localhost:300 and inspect the console. Array of users details should be displayed.

Displaying users on a table.

src/components/Users.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// truncated
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(res => res.json())
      .then(json => {
        this.setState({ users: json });

      });

  }
render() {
    let { users } = this.state;
    return (
      <div>
        <table>
          <tr>
            <th>Name</th>
            <th>Email Address</th>
            <th>Phone Number</th>
            <th>Website</th>
          </tr>



        {users.map((user) => {
          return (

            <tr>
            <td>{user.name}</td>
            <td>{user.email}</td>
            <td>{user.phone }</td>
            <td>{user.website}</td>
            </tr>


          );
        })}
        </table>
      </div>
    );
  }

We first of all set the state of our users array which was initial empty to be the array we get from the response as indicated in line 6.

Exercise

From JSONPlaceholder. Perform the following operations on Post resource.

  1. List all available posts
  2. Create a post
  3. Update and existing post
  4. Delete an existing post