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.
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.
Next: A CLI in both
Article author: Arthur Isaev