REST APIs

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.

The examples use api.example.com as a placeholder: point them at your own API, with a real token, before you run them.

require "net/http" require "json" uri = URI("https://api.example.com/users/1") data = JSON.parse(Net::HTTP.get(uri)) puts data["name"]

With the placeholder still in place the name does not resolve, so the request raises Socket::ResolutionError, a kind of SocketError, and the parse never runs.

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"]

The placeholder host raises the same Socket::ResolutionError here, and the response code is never reached.

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"]

The request fails with Socket::ResolutionError before a single header is read, because the host is still the placeholder.

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

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does this program print? require "json" data = JSON.parse('{"id": 7, "name": "Ada"}') puts data["id"] puts data["name"]

    Answer

    7 / Ada

    A JSON number becomes an Integer and a JSON string becomes a String, and puts prints both without quotes.

  2. What does this program print? require "json" payload = JSON.generate({ name: "Ada", role: "admin" }) puts payload

    Answer

    {"name":"Ada","role":"admin"}

    generate writes compact JSON text, and symbol keys become quoted names.

  3. What does this program print? require "uri" base = "https://api.example.com" uri = URI(base + "/users/1") puts uri.host puts uri.path

    Answer

    api.example.com / /users/1

    host is the name alone and path is everything after it, starting with the slash.

  4. What does this program print? require "net/http" uri = URI("https://api.example.com/users/1") request = Net::HTTP::Get.new(uri) request["Accept"] = "application/json" puts request["Accept"]

    Answer

    application/json

    A request header can be set and read by name, and the value is the string that was stored.

  5. What does this program print? require "net/http" request = Net::HTTP::Post.new("/users") request["Content-Type"] = "application/json" puts request.method puts request["Content-Type"]

    Answer

    POST / application/json

    The class decides the method, and the header is what was set on the object.

  6. Which header carries a bearer token?

    Answer

    Authorization

    The token travels as Authorization: Bearer TOKEN, which is what the request object sets.

  7. What does a 201 status mean for a POST?

    Answer

    The record was created

    The success status of a creation is 201, and the body often carries the new id.

  8. Why does the client use Net::HTTP.start(uri.host, uri.port, use_ssl: true)?

    Answer

    To open the connection with TLS and reuse it for the request

    start opens the connection with the SSL setting that the https URL needs.

  9. What does response["Content-Type"] read?

    Answer

    A header of the response

    The response object answers header names, and the body is a separate method.

  10. What does JSON.parse(Net::HTTP.get(uri)) produce for a JSON object?

    Answer

    A Ruby hash with string keys

    The parsed object becomes a hash, and its keys are the names as strings.

Article author: Arthur Isaev