Creating a custom http service provider for React

Creating a custom http service provider for React

When we want to call API endpoints, pass in tokens to headers, define content type and connect to servers with the necessary configuration, we do this in our axios/fetch params per call however this method is quite dirty and some times the developer can run into errors and frustration. Frameworks like flutter and Angular come with their own http service, however react does not.

In this article we are going to be building a reusable http service for our react app do all the necessary configurations in one file and export our http methods.

Step by Step Guide line

  1. We start by creating a new file in our src folder name httpService.js

  2. Install and import axios in our httpService.js file

    import axios from "axios'
    
  3. We export our 3 CRUD methods as default PUT, DELETE, GET, POST
import axios from "axios'
export default { 
get:axios.get,
post:axios.post,
delete: axios.delete,
put: axios.put
}

Calling protected API endpoints

This are end points that require us to send something to the backend most times a jwt instead of passing in the jwt in every request we can handle this just once in our httpService.js file.

import axios from "axios'

axios.defaults.headers.common["Authorization"]=AUTH_TOKEN;
//we could also do axios.defaults.headers.post this will handle post requests
axios.defaults.headers.common['Content-Type'] = 'application/json';

export default { 
get:axios.get,
post:axios.post,
delete: axios.delete,
put: axios.put
}

Whenever we have a http request this token is parsed to the header if the AUTH_TOKEN is undefined the token will not be set to the headers.

We can now test our application by

import http from "./httpService"
const apiEndpoint ="YOUR ENDPOINT URL HERE"

const login=async(user)=>{
  const data= await http.post(apiEndpoint,user);
}

We no longer need to pass in header configurations into our http.get() call any more, it is now handled globally.

This is more like a crash course on axios and configuring your own httpService to read more on axios check here

Happy Coding, Thank you for reading.