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

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

Banner image