How to use SERP API for google data in ReactJs

If you want to create a website that has something to do with google maps API then you need to create a billing account on a google cloud platform and then you will get access to use google maps API. I wanted to do the same but don't want to create a billing account so I found an alternative to google maps API and that is SERP API which allows free 100 api calls/month.

Here I will show how to create a website using ReactJs and NodeJs that fetches the places data from the address and type of place the user wants to go.

Some things to keep in mind

  1. CORS policies don't allow us to make a direct api call to a different platform and get the data, you can read about it here so we will be using Axios in the frontend to get to the node router in the backend, where it is making an api call and sending the response.

  2. Error handling is mandatory because you will never know the status code of the api response otherwise code can break at that time.

Step -1: Create a backend

  1. First of all, you have to create an express app in the backend directory and set the app headers as shown below to prevent from network errors.
const axios = require('axios');
const express = require('express');
const app = express();
app.use((req, res, next) => {
    res.set("Access-Control-Allow-Origin", "*");
    res.set("Access-Control-Allow-Headers", "*");
    res.set("Access-Control-Allow-Methods", "*");
    res.set("x-requested-with", "XMLHttpRequest");
    res.set("Access-Control-Expose-Headers","Content-Encoding,api_key");
    res.set("origin","http://localhost:3000");
    if (req.method === "OPTIONS") {
        res.status(200).end();
        return;
    }
    next();
});
  1. Create a post request route to call a serp api for the required address and type of place.

     app.post("/", (req, res) => {
         let {addressName, placeName} = req.body;
         axios.get(`https://serpapi.com/search.json?engine=google&q=${placeName}&location=${addressName}&google_domain=google.com&gl=us&hl=en&api_key=your_api_key`)
             .then(function (response) {
                 res.send(response.data);
             })
             .catch(function (error) {
                 res.send(error.response.data);
             });
     });
    
  2. Start backend on port 5000

     app.listen(5000, ()=>{
         console.log("app is listening on port 5000");
     });
    

Step -2: Create a frontend

  1. Create an input field to take the address of a user and the type of place he/she wants to go.

           <div className="mainList">
             <div className="searchBox">
               <form onSubmit={handleSubmit} action="">
                   <label htmlFor="Address">Address</label>
                   <br />
                   <input
                     type="text"
                     className="addressInput"
                     value={address}
                     name="address"
                     onChange={(e) => setAddress(e.target.value)}/>
                   <label for="typeofplace">Type of Place </label>
                   <br />
                   <select
                     value={place}
                     onChange={handleChange}
                     className="placeSelection"
                     name="place"
                     id="place"
                   >
                     <option value="cafe" selected>Cafe</option>
                     <option value="restaurant">Restaurant</option>
                     <option value="pizza">Pizzeria</option>
                     <option value="dosa/idli">South Indian</option>
                   </select>
                 <button className="searchBtn">Find</button>
               </form>
             </div>
           </div>
    
    1. Request to 5000 port to get the required data from API and save the response in react hooks.

       const [outcomeData, setData] = useState([]);
       const [error, setError] = useState("");
       const handleSubmit = (e) => {
           e.preventDefault();
           var userdata = {
             addressName: address,
             placeName: place,
           };
           axios({
             method: "POST",
             url: `http://localhost:5000/`,
             headers: {
               "Content-Type": "application/json",
               "Access-Control-Allow-Origin": "*",
               "Access-Control-Allow-Methods": "*",
               "x-requested-with": "XMLHttpRequest",
             },
             data: userdata,
           })
             .then((res) => {
               if (res.data.error) {
                 setError(res.data.error);
                 setData([]);
               } else {
                 setData(res.data.local_results.places);
                 setError("");
               }
             })
             .catch((e) => {
               alert(e);
             });
         };
      
    2. The response will look like this so you can map outcome data in React as you want in react components.

Wrapping up

That's it for this blog I hope this blog helped you in some way. My motivation to write this blog was that there was no good source on youtube or google to learn about serp api. Here is github repo link if someone wants to go through the whole project code.

Thank you for reading !!