HTTP and JSON in both

A local JSON endpoint

The task needs a URL that returns JSON and stays put, so both versions call a local server instead of the internet. Four lines with WEBrick are enough:

require "json" require "webrick" user = { "name" => "Ada", "role" => "admin" } server = WEBrick::HTTPServer.new(Port: 8000) server.mount_proc("/user.json") do |_req, res| res["Content-Type"] = "application/json" res.body = JSON.generate(user) end server.start

With the server running, the endpoint answers one compact object:

python3 -c 'import urllib.request; print(urllib.request.urlopen("http://localhost:8000/user.json").read().decode())'

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

Ruby

require "json" require "net/http" body = Net::HTTP.get(URI("http://localhost:8000/user.json")) user = JSON.parse(body) puts user["name"]

ruby fetch.rb

Ada

Python

import json import urllib.request with urllib.request.urlopen("http://localhost:8000/user.json") as response: user = json.loads(response.read()) print(user["name"])

python3 fetch.py

Ada

Both print the same field from the same response. The Ruby version is one method call that returns the body as a string; the Python version opens a response object and reads it, which is also where a timeout and a status check would go. Run the client before the server and it stops with Errno::ECONNREFUSED, which is the error the timeout and the status check exist to replace.

What differs

Neither standard library is what a large project uses: Ruby projects reach for Faraday or HTTParty, Python projects for requests or httpx. The shape stays the same: build a request, read a body, parse JSON, check the status.

Questions

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

  1. What does JSON.parse return in Ruby?

    Answer

    A hash whose keys are strings

    The keys stay strings, which is why the code writes user["name"] and not user[:name].

  2. What does this program print? require "json" body = '{"name":"Ada","role":"admin"}' puts JSON.parse(body)["name"]

    Answer

    Ada

    The parse turns the body into a hash and the key reads the value, which is what the HTTP client version prints too.

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

    Answer

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

    generate writes the compact form with string keys, the shape the local endpoint answers with.

  4. What does this program print? require "json" user = JSON.parse('{"id":1,"tags":["a"]}') p user["tags"]

    Answer

    ["a"]

    A JSON list becomes a Ruby array, and p shows it with its quotes and brackets.

  5. What does this program print? require "uri" p URI("http://localhost:8000/user.json").path

    Answer

    "/user.json"

    The URI splits the address, and path is the part a server routes on.

  6. What does Python's urllib.request.urlopen return?

    Answer

    The body as a string

    The body comes from the response object as bytes, which then goes to json.loads or needs decoding.

  7. What does this program print? require "json" begin JSON.parse("{") rescue JSON::ParserError => e puts e.class end

    Answer

    JSON::ParserError

    A broken body is a parser error, and the rescue names the class a client has to catch.

  8. How does Python treat a non-2xx response from urlopen?

    Answer

    As an exception, unlike Ruby's Net::HTTP object

    The exception means the Python version needs its try block around the call itself, not only around the parse.

  9. What does this program print? require "json" p JSON.parse('{"a":{"b":2}}')["a"]["b"]

    Answer

    2

    Each level is a hash, and the second key reaches the number at the bottom.

  10. Which libraries do large projects use instead of the standard clients?

    Answer

    Faraday or HTTParty in Ruby, requests or httpx in Python

    The standard clients are enough for one request, and the ecosystem builds on them for retries, pools and timeouts.

Article author: Arthur Isaev