DEV Community

milanwinter
milanwinter

Posted on

Making Api Calls through a Rails backend to React frontend

Why Use Rails?

If you've unsuccessfully tried to make api calls from a React/Js frontend, you may have gotten a CORS error. Well what's happening is that many Apis actually block calls that are made directly from the browser. Well here is where Rails comes in in all of its glory. Using a Rails api backend allows you to make calls to the Api from Rails without running into CORS errors.

Setting up Rails-Api

Rails is amazing, in that it can be built as an API only by using the following command.
Screen Shot 2021-03-11 at 2.15.11 PM
This command limits what Rails generates in in terms of views and helpers and so on essentially giving you only the things that you need to be able to make your api calls.

Hiding the Api-Key

I found that the easiest way to hide your API key is by using the Figaro gem because it basically does all the work for you. All you have to do is add the Figaro gem with the command "$ bundle exec figaro install". The gem will automatically create a file called Application.yml and add it to your gitignore file for you.Next declare your api key within that file like this.
Screen Shot 2021-03-11 at 5.57.26 PM

Now all you have to do is add Application.yml to your gitignore file and your api key is hidden!
Screen Shot 2021-03-11 at 5.37.53 PM

Retrieving the API Key

In order to retrive your api key it's quite simple. You simply have to declare a variable in whatever function you're trying to make the api call.
Screen Shot 2021-03-11 at 5.55.49 PM
Now you can interpolate that variable in your api call in whatever way you need! Here is an example!
Screen Shot 2021-03-11 at 5.57.52 PM

Setting up Your Route

The last thing you want to do is set up a route for you api call. On the last project I worked on, I was making api calls to a weather app to get forecasts for ski resorts that I could send up to my front end. Here is what my custom route looked like to get information to a single. Now because the api needed a specific apiId for each ski resort, I designed my front end in a way that would allow me to get the apiId for each resort through my route.
Screen Shot 2021-03-11 at 2.21.22 PM

Conclusion

And thats all there is to it! Although your api calls may be different, you always want to make sure that you're hiding your api key because if you make a commit and you haven't hidden it, you'll run into issues.

Top comments (0)