Capstone: JSON API

Contents
The spec
WEBrick routes
JSON handlers
Test with Net::HTTP

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

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: