• Brooke Bachman

Fetching to an Api on The Backend

Updated: May 4

For my final project at Flatiron, I decided to conquer my fear of working with an outside API on my own.

I tried 3 different Google Maps APIs.

I decided GooglePlaces Text Search was the one that offered the results I was looking for.

I successfully got the API to fetch the data on the frontend.

I found out that fetching from an outside API is not as secure, and it is fairly difficult to properly hide your API key.

So, I decided I would try something new, sending an HTTP request from my backend.

In my project, I am fetching all of the birth centers within a certain radius of the user's location to give the search results closest to them.

First, you need to add the rest-client gem to your gemfile.

This allows you to make an HTTP request in Rails.

In my birth_centers_controller I created an Index Method.

RestClient allows us to make HTTP requests from the backend. It has all of the crud methods.

In order to use RestClient you must specify what type of HTTP request it is.

The RestClient.get fetches the data and returns a promise just like fetch in javascript. If that HTTP request is successful you get a string.

In my google maps URL I need to include the latitude and longitude that I want to be the beginning point for the radius of locations I want to see.

I actually get the latitude and longitude from my frontend. They are stored in the params so the way to access them is by using their keys.

You enter in your URL, with your parameters and your Apikey.

I stored my API key in a .env file and added the .env file to the gitignore folder.

The way to access the Apikey once you have stored it in the .env file is to interpolate it #{ENV['your_api_key_name_variable']}

Next you create a variable to convert the response from the HTTP request to JSON.

I am using a serializer so now I want to render Json with the variable I created as you see in line 32.

Now you need to have a route to that controller method.

get '/birthcenters', to: 'birthcenters#index'

On the frontend I can now fetch to my backend.

The parameters I need for the fetch are longitude and latitude, so I add those to the request.

I am using React as my frontend so I am setting the initial state of places to an empty array.

In my fetch request, I am setting the state to the data I am getting back from the request.

The data that I wanted was nested within a hash. I needed the array that was the value of the results key so I use data.results to access the array of places from the google API.

That is all you need to make your fetch to the outside API on your backend.