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.

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

Next: Performance

Article author: Arthur Isaev