Engineering

Mastering REST API Setup: Configuring Package.json & Environment Settings

-By Sushil Kundu

 

Hey there, fellow developers! Ever found yourselves tangled up in the intricacies of setting up a REST API project? Or perhaps, found it tricky to get your package.json file just, right? Well, you're not alone. These crucial steps form the bedrock of any smooth-sailing development and deployment process. So, buckle up, as we're about to take a deep dive into a streamlined approach that will put these challenges to rest, once and for all!

Key Steps

Creating a common configuration for your REST API project and tailoring the package.json file can be achieved in a few simple steps:

Deep Dive

So, you know how we sometimes wish to run different commands based on our environment, right? Well, we can do just that with the help of environment-specific configurations! It's like having a little magic wand that tailors your commands to suit your environment. And the best part? It's all happening right in your package.json file.

Alright, let's look at an example. But before diving in, remember this – we will use a neat little package called "cross-env" to set our NODE_ENV variable. Now, here's what your package.json file might look like:

 

json

 

 

{

 "name": "your-app",

 "version": "1.0.0",

 "scripts": {

  "start:dev": "cross-envNODE_ENV=development react-scripts start",

  "start:qa": "cross-envNODE_ENV=qa react-scripts start",

  "start": "npm runstart:dev",

  "build:dev": "cross-envNODE_ENV=development react-scripts build",

  "build:qa": "cross-envNODE_ENV=qa react-scripts build",

  "build": "npm runbuild:dev"

 },

 "dependencies": {

   ...

 },

 "devDependencies": {

   ...

 }

}

 

We've set up separate "start" and "build" scripts for our development and QA environments:

 

So, next time you want to run your app in the development or QA environment, you can just call on these commands with 'npm run start:dev' or 'npm run start:qa'.

Similarly, to build the app with the desired environment, you can use the following command: npm run build:dev or npm run build:qa. And the best part? By default, the regular 'npm start' or 'npm run' will get you rolling in the development environment.

To define the base path for development and QA environments in the .env file and update the condition in the config.js file accordingly, you can follow these steps:

 

Step 1: Create a .env file in the root of your project and define the base paths for development and QA environments:

 

REACT_APP_BASE_PATH_DEV=http://dev.example.com/api

REACT_APP_BASE_PATH_QA=http://qa.example.com/api

 

Step 2: Update the config.js file to read the base paths from the .env file and use the appropriate base path based on the environment type. Here's an updated version of config.js:

 

const env =process.env.NODE_ENV || 'development';

 

let basePath;

if (env ==='development') {

 basePath =process.env.REACT_APP_BASE_PATH_DEV || '';

} else if (env ==='qa') {

 basePath = process.env.REACT_APP_BASE_PATH_QA|| '';

} else {

 basePath = ''; // Default base path

}

const config = {

 basePath,

 relativePath: '/data',

 commonHeader: {

   Authorization: 'Bearer your token,

   'Content-Type': 'application/json',

 },

};

 

export functionbuildUrl(relativePath, queryParams, requestParams) {

 const url = basePath + relativePath;

 const params = queryParams ? newURLSearchParams(queryParams).toString() : `/${ requestParams }`;

 return queryString ? `${url}?${ params }` :url;

}

 

export defaultconfig;

 

Our revamped config.js file is now super smart! How? It's got the power to read the NODE_ENV environment variable and understand what environment we're playing in. So, it goes ahead and assigns the base Path based on this environment type. It finds the right base path from the .env file using those REACT_APP_BASE_PATH_DEV and REACT_APP_BASE_PATH_QA variables.

 

So, what does this mean for you? Simply, when you're running your app in different environments, your config.js file is like your personal chameleon! It changes its colors, or more accurately, its base path, based on the environment type specified in that .env file. Ever wanted to create a dummy API request using Axios? Well, here's your golden ticket. And it's way simpler than you think. We'll be using our given configuration and some nifty URL-building functions to get there. Just follow these steps:

 

 

Step 1: Install Axios in your project:

 

npm install axios

 

Step 2: Create a new file, e.g., api.js, and import the necessary modules:

 

import axios from'axios';

import config, {buildUrl } from './config.js';

 

Step 3: Define a function tomake the API request:

 

async function makeApiRequest(relativePath,queryParams) {

 try {

   // Build the URL with query parameters

   const url = buildUrl(relativePath,queryParams);

 

   // Make the API request

   const response = await axios.get(url, {

     headers: {

       common: config.commonHeader,

     },

   });

 

   // Process the response

   console.log('API response:',response.data);

 } catch (error) {

   // Handle any errors

   console.error('API request failed:',error);

 }

}

 

Usage example:

 

const queryParams = {param1: 'value1', param2: 'value2' };

makeApiRequest('/data',queryParams);

 

Here's the thing about the make ApiRequest function - it's a pretty flexible fellow. It takes in two parameters, relative Path, and queryParams.

Say, for example, you want to make an API request to the '/data' relative path, with some query parameters. You just need to call make ApiRequest('/data', queryParams), and boom! It's done.

But here's the catch- you have to ensure that your build Url function in your config.js file is implemented correctly. It's like building a house, the foundation needs to be solid for the house to stand firm. Similarly, build Url constructs the complete URL using the relative path and query parameters, serving as the backbone for your API requests.

So, make sure you've got build Url set up right. Once you do, making API requests with make ApiRequest will be as smooth as slicing through butter.

But do remember to adjust the code according to your specific application requirements.

Note: Make sure you have the necessary dependencies (such as dot env for reading the .env file)installed in your React app. Also, the .env file variables starting with REACT_APP_ are automatically loaded into process .env in React apps.

Final thoughts

By sticking to these steps, you can cut through the chaos and streamline the setup of your API project's configuration and package.json file like a pro. No more sleepless nights over managing environment-specific settings! With our trusty guide by your side, you'll be handling those settings like a boss, creating dynamic URLs that work like magic, and firing off API requests using Axios - all in a day's work.

What's the cherry on top, you ask? All this wizardry doesn't just make your coding life easier, it actually takes your entire project development and deployment process up a notch. Now, that's what we call a win-win! So, gear up and dive into transforming the way you manage your API project. Here's to easier, faster, and more efficient coding!

You may also like