[Ruby] Get data with api created by curl command

1 minute read

environment

cloud9 (api acquisition side) local (api provider) ruby 2.6.3 Rails 6.0.2.1

Conclusion

controller

def index
  uri = `curl -v -X GET "http://stage-smartyoyaku-env.ap-northeast- 1.elasticbeanstalk.com/api/v1/tasks" \
        -H "Authorization: Bearer Write Token here"`
  @test = JSON.parse(uri)
end

*Check in your browser if you have acquired

viewfile

<%= @test %>

Error content up to that point

Enter the curl command in the cloud9 terminal. ..

curl: (7) Failed to connect to localhost port 3000: Connection refused

It looks like the server is not up or the port number is wrong. I accessed localhost:3000 with a browser, but there is no problem. There was also a port number,

Organize again

・The curl command is hit in the application on the cloud9 side. (Obtainer) ・Launching an application that provides api with 3000 port in local environment. (Providing side) ← Important here

Hmm? I can’t connect to local from cloud9 (on the internet),

$ lsof -i:3000
$

Check if 3000 port is used on cloud9 → it is not displayed

That is, the side providing the api needs to publish the url to the net with heroku etc. and fetch the data from it.

important point

There are subtle differences in how to write the curl command in the terminal and when writing to the controller. In controller, curl command is enclosed in ``.

In case of terminal

$ curl -v -X GET "http://stage-smartyoyaku-env.ap-northeast-1.elasticbeanstalk.com/api/v1/tasks" \
          -H "Authorization: Bearer Write Token here"
For controller

def index
  uri = `curl -v -X GET "http://stage-smartyoyaku-env.ap-northeast- 1.elasticbeanstalk.com/api/v1/tasks" \
        -H "Authorization: Bearer Write Token here"`
end