Capstone: JSON API

The spec

The second capstone turns the todo list into a tiny web API. GET on todos returns the list as JSON, while POST on todos appends a new item.

WEBrick hosts the API and the json library encodes every response, so the whole project stays inside the standard library.

curl http://localhost:8000/todos

[]

WEBrick routes

Routes are mounted paths with a block per path. One mount point serves the whole todos collection for this small API.

The block receives the request and the response on every call, which keeps routing and handling in one readable place.

require "webrick" server = WEBrick::HTTPServer.new(Port: 8000) server.mount_proc("/todos") do |_req, res| res.body = "ok" end server.start

JSON handlers

Handlers branch on the request method and speak JSON on both sides. GET encodes the array, while POST parses the body and appends the new hash.

Always set the JSON content type so clients parse the body without guessing the format.

require "webrick" require "json" items = [] server = WEBrick::HTTPServer.new(Port: 8000) server.mount_proc("/todos") do |req, res| res["Content-Type"] = "application/json" if req.request_method == "GET" res.body = JSON.generate(items) end if req.request_method == "POST" data = JSON.parse(req.body) items << data res.body = JSON.generate(data) end end server.start

Test with Net::HTTP

Test the running API with Net HTTP from a second terminal. A GET call returns a body string that JSON parse turns back into an array.

Start the server first, then run the snippet below and confirm an empty array on a fresh start. Run it while nothing listens and it stops with Errno::ECONNREFUSED, which is the failure the test reports.

require "net/http" require "json" res = Net::HTTP.get(URI("http://localhost:8000/todos")) puts JSON.parse(res).inspect

Questions

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

  1. What does server.mount_proc("/todos") { |req, res| ... } do?

    Answer

    Mounts a block that runs for every request whose path is /todos

    The mount point is the route, and the block receives the request and the response of every call to it.

  2. What does this program print? require "json" items = [{ "title" => "a" }] puts JSON.generate(items)

    Answer

    [{"title":"a"}]

    The compact form is what the API writes into the body, and the keys keep their quotes.

  3. What does this program print? require "json" data = JSON.parse('{"title":"buy"}') p data["title"]

    Answer

    "buy"

    The parsed body is a hash with string keys, and p prints the string with quotes.

  4. What does this program print? method = "GET" puts(method == "GET" ? "list" : "create")

    Answer

    list

    The handler branches on the request method, and GET is the list branch of the API.

  5. What does this program print? headers = { "Content-Type" => "application/json" } p headers.fetch("Content-Type")

    Answer

    "application/json"

    Set the content type on every response so a client parses the body without guessing.

  6. What does this program print? require "json" res = "[]" puts JSON.parse(res).inspect

    Answer

    []

    The body string parses to an empty array, and inspect writes it the way a terminal shows it.

  7. Why does the API set the JSON content type on both branches?

    Answer

    So the client parses the body as JSON without guessing the format

    The header is the contract of the response, and a client that trusts it can parse every branch the same way.

  8. What does this program print? items = [] items << { "title" => "a" } p items.size

    Answer

    1

    The POST branch appends one hash to the array the server holds in memory.

  9. Why does the test use Net::HTTP from a second terminal rather than reading the source?

    Answer

    Because a running server is the thing being tested

    The request goes through the server, the router and the handler, which is the path a client takes.

  10. What does this program print? require "json" puts JSON.generate({"ok" => true})

    Answer

    {"ok":true}

    The response body is the compact JSON text, and puts writes it without the quotes p would add.

Article author: Arthur Isaev