[RAILS] [Ruby] Use an external API that returns JSON in HTTP request

Thing you want to do

I want to use an external API in Ruby that makes an HTTP request and returns JSON. I want to get a hash that can be used in Ruby from JSON.

Conclusion

#Load various libraries
require 'net/http'
require 'json'
require 'uri'

#uri library>URI module
#Generate and return the corresponding instance
uri = URI.parse('http://hoge.com')
# => #<URI::HTTP http://hoge.com>

#net/http library>Net::HTTP class
#Send a GET request to the URL and send the body"String"Returns as.
json = Net::HTTP.get(uri)

#joson library>JSON module
#Convert the obtained JSON format character string to a Ruby object and return it
JSON.parse(json)

With the above, you can send a GET request to the URL and get a hash that can use JSON format data in Ruby.

Official reference

URI Module Net :: HTTP class JSON module

What is JSON

JavaScript Object Notation (JSON, Jason) is one of the data description languages. It is a lightweight text-based data exchange format that can be used in any programming language [1]. The name and syntax are derived from the notation of objects in JavaScript. https://ja.wikipedia.org/wiki/JavaScript_Object_Notation

It is used not only for JavaScript but also for data exchange between various languages ​​such as Java, PHP, Ruby, Python, especially Ajax and REST API. In the past, XML was used as a common data definition language, but nowadays, simple JSON is increasingly used. http://www.tohoho-web.com/ex/json.html

It is a description format for exchanging data between different languages, and the notation is derived from JavaScript. In the past, XML was used when exchanging data, and JSON is now the mainstream.

JSON rules

A colon is attached to the key and value. Enclose the string in " " double quotes. { "hoge": "fuga" }

Single quotes cannot be used. ❌{ 'hoge': 'fuga' }

You can specify multiple keys and values ​​by using commas { "hoge": "fuga", "foo": 123 }

Only arrays and values ​​are OK! ["hoge","fuga"] "hoge" 123

Summary

I got JSON from API and briefly summarized how to use it in Ruby and JSON.

Recommended Posts

[Ruby] Use an external API that returns JSON in HTTP request
Display weather forecast using OpenWeatherMap, an external API in Ruby
[RSpec] Use WebMock to test logic using an external API
Generate AWS Signature V4 in Java and request an API
Use Face API from Ruby
Use ruby variables in javascript.
[Ruby] Method that returns truth
Released an API that can use Sentence Piece like morphological analysis
[Rails] Use cookies in API mode
Run an external process in Java
[Ruby / Rails] Use alias. In a way that rubocop won't get angry!
A story about an arithmetic overflow that you shouldn't encounter in Ruby