REST APIs

Contents
GET JSON
POST JSON
Headers and status
A tiny client class

GET JSON

Most public APIs answer with JSON, so parse the body right after the GET request.

JSON.parse turns the JSON text into hashes and arrays that Ruby code can read.

require "net/http" require "json" uri = URI("https://api.example.com/users/1") data = JSON.parse(Net::HTTP.get(uri)) puts data["name"]

POST JSON

Writing data works the same way in reverse: generate a JSON string and post it with a header.

The response code tells whether the server created the record, and the body often carries the new id.

require "net/http" require "json" uri = URI("https://api.example.com/users") payload = JSON.generate({ name: "Ada", role: "admin" }) response = Net::HTTP.post(uri, payload, { "Content-Type" => "application/json" }) puts response.code puts JSON.parse(response.body)["id"]

Headers and status

Real APIs need more than a body: tokens travel in headers and meaning travels in the status code.

Build a request object to attach headers, then send it through Net::HTTP.start with SSL enabled.

require "net/http" uri = URI("https://api.example.com/users") request = Net::HTTP::Get.new(uri) request["Authorization"] = "Bearer TOKEN" request["Accept"] = "application/json" response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| http.request(request) end puts response.code puts response["Content-Type"]

A tiny client class

A tiny client class keeps the base URL and the token in one place and returns raw responses.

A Russian-language REST deep dive lives at REST API requests (in Russian) when you want a second worked example.

require "net/http" require "json" class ApiClient def initialize(base_url, token) @base_url = base_url @token = token end def get(path) uri = URI(@base_url + path) request = Net::HTTP::Get.new(uri) request["Authorization"] = "Bearer #{@token}" Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http| http.request(request) end end end client = ApiClient.new("https://api.example.com", "TOKEN") puts client.get("/users/1").code

Next: puts, print and p

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
Banner image

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: