DEV Community

Cover image for How To Use an API from your Ruby Server
Xauvkub Alex Yang
Xauvkub Alex Yang

Posted on

How To Use an API from your Ruby Server

Step 1
USE RESTCLIENT TO FETCH FROM API
The first thing we want to do is fetch from the API.

def from_api
 resp = RestClient.get("https://exampleapi.com/?api_key=1241241515151")
 render json: resp.body, status: :ok
end
Enter fullscreen mode Exit fullscreen mode

Step 2
HIDE YOUR API KEY
If you need to hide your key you can do so by using a gem called Figaro.

gem "figaro"
Enter fullscreen mode Exit fullscreen mode

Add figaro to to your gemfile, bundle install figaro and install figaro.

$ bundle exec figaro install
Enter fullscreen mode Exit fullscreen mode

This creates a config/application.yml file and adds it to your .gitignore. You can use this to create Environment variables such as your key.

api_key: 1241241515151 (example)
Enter fullscreen mode Exit fullscreen mode

And you can call it like this.

ENV['api_key'] 

> 1241241515151
Enter fullscreen mode Exit fullscreen mode

Now use that key in your fetch request.

def from_api
    resp = RestClient.get("https://exampleapi.com/
?api_key=#{ENV['api_key']}")
    render json: resp.body, status: :ok
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)