REST APIs
| GET JSON | |
| POST JSON | |
| Headers and status | |
| A tiny client class |
GET JSON
Most public APIs answer with JSON, so parse the body right after the GET request.
JSON.parse turns the JSON text into hashes and arrays that Ruby code can read.
require "net/http"
require "json"
uri = URI("https://api.example.com/users/1")
data = JSON.parse(Net::HTTP.get(uri))
puts data["name"]
POST JSON
Writing data works the same way in reverse: generate a JSON string and post it with a header.
The response code tells whether the server created the record, and the body often carries the new id.
require "net/http"
require "json"
uri = URI("https://api.example.com/users")
payload = JSON.generate({ name: "Ada", role: "admin" })
response = Net::HTTP.post(uri, payload, { "Content-Type" => "application/json" })
puts response.code
puts JSON.parse(response.body)["id"]
Headers and status
Real APIs need more than a body: tokens travel in headers and meaning travels in the status code.
Build a request object to attach headers, then send it through Net::HTTP.start with SSL enabled.
require "net/http"
uri = URI("https://api.example.com/users")
request = Net::HTTP::Get.new(uri)
request["Authorization"] = "Bearer TOKEN"
request["Accept"] = "application/json"
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
http.request(request)
end
puts response.code
puts response["Content-Type"]
A tiny client class
A tiny client class keeps the base URL and the token in one place and returns raw responses.
A Russian-language REST deep dive lives at
REST API requests (in Russian)
when you want a second worked example.
require "net/http"
require "json"
class ApiClient
def initialize(base_url, token)
@base_url = base_url
@token = token
end
def get(path)
uri = URI(@base_url + path)
request = Net::HTTP::Get.new(uri)
request["Authorization"] = "Bearer #{@token}"
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
http.request(request)
end
end
end
client = ApiClient.new("https://api.example.com", "TOKEN")
puts client.get("/users/1").code
Next: puts, print and p
Article author: Arthur Isaev