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
- The client. Ruby ships Net::HTTP with a one-line get that returns the body. Python ships urllib.request, whose urlopen returns a response object; the body is a bytes value and needs decoding or, as here, goes straight into json.loads.
- Parsing. JSON.parse against json.loads: the same idea, one returns a Ruby hash with strings as keys, the other a Python dict.
- Errors. A missing host raises SocketError in Ruby and urllib.error.URLError in Python; a non-2xx response is an ordinary object in Ruby and an exception in Python. The Python version needs the try block earlier, not later.
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.
-
What does
JSON.parsereturn 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].
-
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.
-
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.
-
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.
-
What does this program print?
require "uri" p URI("http://localhost:8000/user.json").pathAnswer
"/user.json"
The URI splits the address, and path is the part a server routes on.
-
What does Python's
urllib.request.urlopenreturn?Answer
The body as a string
The body comes from the response object as bytes, which then goes to json.loads or needs decoding.
-
What does this program print?
require "json" begin JSON.parse("{") rescue JSON::ParserError => e puts e.class endAnswer
JSON::ParserError
A broken body is a parser error, and the rescue names the class a client has to catch.
-
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.
-
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.
-
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