0Pricing
Ruby Academy · Lesson

JSON APIs

Returning JSON.

Why JSON APIs?

JSON is the standard data format for web APIs. Clients send and receive structured data instead of HTML.

  • Language independent
  • Maps cleanly to Ruby hashes and arrays
  • Lightweight and human readable

Ruby's standard library handles JSON via the json module.

require 'json'

data = { name: 'Ada', langs: ['Ruby', 'Python'] }
puts data.to_json

Converting Ruby to JSON

Call to_json on a hash or array, or use JSON.generate.

  • Symbols and strings become JSON keys
  • Nested structures convert recursively
require 'json'

user = { id: 1, active: true, tags: ['admin'] }
puts JSON.generate(user)

All lessons in this course

  1. Sinatra Basics
  2. Routes and Params
  3. JSON APIs
  4. Middleware and Rack
← Back to Ruby Academy