Introduction To An Api

Introduction To An Api

The concept of API is one that made me confused for a long time. While in school during our course on operating system was the first time I really came across the topic API meaning Application Programming Interface.

API denotes the pattern with which a program or an application running on the computer at that particular moment requests services or devices from the operating system to execute a particular task. I never knew this concept extends beyond the operating system. It’s all over the web. Fintech companies software request data from payment gateway, banks software request data from betting companies to carry out certain tasks and so on. In this short article, I’ll be using an analogy to describe the significance of an API and how it operates.

ANALOGY OF AN API

While on Facebook recently, I came across a good way of showing what API does. Let us focus on one of those fancy dinner nights where we have guests around the house of the host, we have waiters and waitresses, and then we have the cooks. Now, this is a very good scene to describe what API does. Basically, the idea behind the use of API is fetching data from a server and presenting it in a particular state to the requesting devices which are called clients. These devices can be computers, tablets etc and might not necessarily be a requesting feature of a software, but can also be another software entirely.

Back to our analogy, our guest in the dinner night is a kind of our client devices or third party software requesting for data, while our cooks in the kitchen represent our server who is in custody of all the food and drinks item to be consumed. These food and drink is our data that is to be served to our client computers. That leaves us with our last party which is our waiters, they are responsible for getting the request of our guest, talk to our cooks if such is available, if so, collect the items and present it in an acceptable format to the guest. This analogy is a typical example of how API works.

Depending on the request of our guest, we have different sets of commands; they can get items, give out items, change items or get rid of an item. Similarly, we have commands which our client computers use to perform operation while interacting with our server. In this article we will see the get request, the post request and delete request.

We will be fetching data from JSON PLACEHOLDER, this is an API that gives us blog related data, that is post, userId and so on for development.

GET REQUEST:

Our guest requesting for a particular drink in our analogy is an example of what a GET request does, this is our client or device requesting for a particular data from the server. Let’s get deeper by showing how this can be done using react to request for data from the jsonplaceholder API

useEffect(() => {
        fetch(`https://jsonplaceholder.typicode.com/posts`)
        .then(response => response.json())
        .then(data =>{ setPost(data)})
    }, [])

The above line of code depict how an external API can be called to get a particular piece of information. We are going to be looking at every component

useEffect(() => {

}, [])

The useEffect is a react function that gets called after the DOM is being loaded and the instruction placed within the function is carried out, it’s actually called a functional component, and we also have a class like equivalent known as ComponentDidMount.

fetch(`https://jsonplaceholder.typicode.com/posts`)

The fetch function actually allows us to get a particular piece of data from the API we are trying to call, in our case here, we are trying to get blog post data from the server.

then(response => response.json())

When our data is received, we convert and save it in JSON format. This is a format that is very easy to work with. Its output will be shown later.

.then(data =>{ setPost(data)}){

After our data is gotten, we then save it to an existing array which has been declared previously. Our output is shown below.

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},

POST REQUEST:

Some guests like to bring in their own drink and present as a gift to the host, this drink will be collected and added to the store of drinks. This is known as POST request that is adding a field or record to the existing data in the database. Let’s see how this is done also.

const addPost = (e) => {
    e.preventDefault();

    fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-type': 'application/json',
        },
        body: JSON.stringify({title: title, body:body})
    })
    .then((res) => res.json())
    .then((json) => console.log(json))
},

Once again, we’ll be examining the code above to show what’s really going on and how we can add data to our existing data.

const addPost = (e) => {
    e.preventDefault();  
}

For this, we are using a custom function named addPost to post data to the server. Our function receives one parameter which is an event parameter, and we use this to prevent our page from refreshing when we submit the form.

fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-type': 'application/json',
        },
        body: JSON.stringify({title: title, body:body})
    })

We also use our fetch method once again for posting our data, now the difference between the first and this request is that we are adding a method parameter which has a value of POST indicating we are posting data to the server. We also have header objects as properties and this takes in two parameters here again, the Accept and Content-type property and their values which indicates that we are posting and receiving our data in json format. The JSON.stringify function converts our form field data into json format and passes it to the body property to be submitted.

DELETE REQUEST:

Back to our analogy, if all of our guests are allergic to a particular food or drink, this drink might be requested for it to be removed totally from the store of drink, which is what to delete means. Delete requests delete a particular information or field from the database. Let’s see how this is done

 const deletePost = (id) => {
        fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
            method: 'DELETE'
        });
    }

We also used a custom function for the delete request which takes in the id of the item we are deleting, we also used the fetch method once again but for this case, we append the id of the item we want to delete which was passed as an argument to the function, by adding the method property and Delete value, we indicate that we want that item to be deleted from the database.

PUT REQUEST:

If for example, our guest requested for a martini drink and decided to switch for a Coca-Cola drink, this kind of change is known as PUT request, which is our client changing a particular record or field in the backend of our system. From earlier examples, I would leave it as a guide for you my reader try out yourself and reach me if you have any challenge.

c’est ça