How To Make API calls in Fullstack Apps or React Apps Using Axios
By: Ohuoba Omoruyi David
Tags: React, API, Axios, Mern, Full Stack

API CALLING

When I began programming some years back, APIs, REST APIs and Endpoints were some of the programming concepts that I had the general idea of but didn’t fully understand.

I later took up some internships and came across the term “API” again. This time my colleagues made it seem like an out of this world concept that required 10 years of programming experience and luck from the gods to make work. I felt like the APIs I had been exposed to were wrong just because of the way my internship mentors and online tutorials explained.

But now looking back I realize it’s all the same story: Programmers love overcomplicating the definition of simple concepts.

DEFINITION

An API (Application Programming Interface) is a software/piece of code that allows two separate programmes to interact with each other by passing data with each other.

A simpler definition is: an API is a code that triggers/ causes the transfer of data from one point to another

TYPES

There are two types of APIs that can be configured in your code:

1. ) Internal API:

These are APIs that are configured in full-stack applications. The API is called in the front end requesting for information from the back end server of the same application.

There are typically four operations that can be carried out with APIs. These are called CRUD (Create — POST API Request, Read — GET API Request, Update — PUT/PATCH API Request, Delete- Delete API Request).

We will be focusing on the two main requests, GET and POST, as these are the most widely used.

i.) Internal API GET Request

A GET request means that we are receiving (GETTING) data. An Internal API GET request means we are receiving data from the back end server of the same application.

import axios from "axios" ... axios.get(url) /*state which route/url to get data from*/

.then((res) => {setState(res.data)}) /*do something with data*/

.catch((error) => {console.log(error)}); /*show error if any*/

ii.) Internal API POST Request

A POST request means that we are sending (POSTING) data. An Internal API POST request means we are sending data to the back end server of the same application.

import axios from "axios" ... axios.post(url, "object to be posted")/*state url and data to send*/

.then((res) => {console.log(res.data)}) /*do something with data*/

.catch((error) => {console.log(error)}); /*show error if any*/

2.) External APIs:

These are APIs that are configured in either the front end or back end of applications to interact with an external server. The API is called in the front end/ backend requesting for data or sending data to the server of another individual’s server.

We will be focusing on the two main requests, GET and POST, as these are the most widely used.

To make proper external API requests, make sure you always check the external API’s documentation. However, this is the typical layout:

i.) External API GET Request

A GET request means that we are receiving (GETTING) data. An External API GET request means we are receiving data from the server of another person’s application.

import axios from "axios" ... axios({

method: "get",

url: "https://...../",

headers: {

x-api-key: *key/apikey*

},

"params" : {

custom_params : "custom_param_value"

}

})

.then((data) => {*do something with data*})

.catch((error) => {*do something error*})



ii.) External API POST Request

A POST request means that we are sending (POSTING) data. An External API POST request means we are sending data to an external server.

import axios from "axios" ... axios({

method: "post",

url: "https://...../",

data: {

firstName: 'Peter',

lastName: 'Parker'

},

headers: {

custom_header: *custom_key*

},

params : {

blah_blah: "place param value"

}

})

.then((data) => {*do something with data*})

.catch((error) => {*do something error*})

That’s it for calling APIs

NOTE

In addition, note the following:

Only configure the routes in your backend server if it’s an internal API because External APIs do not require routes in your backend server as it interacts with routes on an EXTERNAL server. For headers and params, they are not always going to be configured in your API.Their requirement(if you should include them or not )will be stated in the external API documentation You can use both internal and external APIs in the same application.

EXTRA:

This is how backend routes are configured for Internal APIs

*These are example Routes/End points. This code is placed in the routes file in the backend server* const mongoose = require("mongoose");

const express = require("express");

const router = express.Router();

const article = require("../models/articlesschema"); router.route("/addarticle").post((req, res, next) => {

return article.create(req.body, (error, data) => {

if(error){

return next(error);

} else {

console.log(data);

res.json(data);

}

});

}); router.route("/").get((req, res)=> {

return article.find((error, data) => {

if(error){

return next (error);

} else {

return res.json(data);

}

});

}); router.route("/edit/:id").get((req,res) => {

return article.findById(req.params.id, (error, data) => {

if (error){

return next (error);

} else {

return res.json(data);

}

});

}); router.route('/update/:id').put((req, res, next) => {

article.findByIdAndUpdate(req.params.id, {

$set: req.body

}, (error, data) => {

if (error) {

next(error);

console.log(error)

} else {

res.json(data)

console.log('User updated successfully !')

}

})

}) router.route("/delete/:id").delete((req, res, next) => {

return article.findByIdAndRemove(req.params.id, (error, data) =>{

if (error){

return next(error);

} else{

return res.status(200).json({

msg: data

})

}

})

}) module.exports = router;

Fin.