create a http server and read the request body as json and return a json response in ruby

You can use the Ruby standard library webrick to create an HTTP server. To read the request body as JSON and return a JSON response, you need to include the json gem in your program. Here's an example code snippet:

main.rb
require 'webrick'
require 'json'

server = WEBrick::HTTPServer.new(Port: 8000)

server.mount_proc '/' do |req, res|
  if req.request_method == 'POST'
    input = JSON.parse(req.body)
    output = { message: "Received your request with input: #{input}" }
    res.status = 200
    res.content_type = 'application/json'
    res.body = JSON.generate(output)
  else
    res.status = 405 # Method Not Allowed
    res['Allow'] = 'POST'
  end
end

trap('INT') { server.shutdown }

server.start
486 chars
22 lines

This code starts an HTTP server on port 8000 and mounts a handler for the root URL. If the request method is POST, it reads the request body as JSON using JSON.parse, creates a JSON response with a message that includes the input, and sets the response status to 200. If the request method is not POST, it sets the response status to 405 and includes an Allow header to indicate that only POST requests are allowed.

You can test this server using curl or any other HTTP client that can send JSON requests.

main.rb
$ curl -X POST http://localhost:8000 -H 'Content-Type: application/json' -d '{"name": "Alice", "age": 25}'
{"message":"Received your request with input: {\"name\":\"Alice\",\"age\":25}"}
187 chars
3 lines

related categories

gistlibby LogSnag