return a json response from a http server with a specific status code in ruby

main.rb
require 'json'
require 'sinatra'

get '/' do
  status 200
  content_type :json
  { message: 'Success' }.to_json
end
116 chars
9 lines

In the above code block, we are using the Sinatra gem to define a simple HTTP server which returns a JSON response with a 200 status code. Here are the steps being followed:

  1. require the necessary libraries for our server - json and sinatra.
  2. Define a route for our server using the get method. This route will match http://localhost:4567/.
  3. Set the HTTP status code of our response to 200 using the status method.
  4. Set the content_type of our response to json.
  5. Create a simple JSON object with a message, and convert it to a JSON string using the to_json method.
  6. Return the JSON string as the body of our HTTP response.

This is a simple example of returning a JSON response with a specific status code from a Ruby HTTP server. The sinatra gem is a lightweight framework for building web applications in Ruby and can be used to define more complex routes and responses.

gistlibby LogSnag