basic-api

Learn how to create a basic API using Ruby

Ruby Basic API Example

Understanding Ruby WEBrick API Development

This example demonstrates how to build a fundamental API using Ruby's built-in WEBrick library. WEBrick is a simple HTTP server toolkit that allows you to create web applications and services directly in Ruby without external dependencies for basic functionality. This guide focuses on setting up a server that can respond to different HTTP methods, providing a foundation for more complex API development.

Handling HTTP Requests with WEBrick

The core of this API is the MyApi class, which inherits from WEBrick::HTTPServlet::AbstractServlet. This class is designed to handle incoming HTTP requests. Each HTTP method (GET, POST, PUT, DELETE) is managed by a corresponding do_METHOD method within the class. These methods receive the request and response objects, allowing you to inspect the incoming request and construct the outgoing response.

Implementing GET, POST, PUT, and DELETE Methods

The provided code illustrates how to implement handlers for the most common HTTP methods:

  • GET: Responds with a simple JSON message "Hello, World!".
  • POST: Parses the JSON body of the request and returns a confirmation message including the received data.
  • PUT: Similar to POST, it parses the JSON body and confirms receipt of the data.
  • DELETE: Responds with a confirmation message indicating a DELETE request was received.

Each method sets the HTTP status code to 200 (OK) and the Content-Type header to application/json, ensuring clients receive responses in the expected format.

Setting Up and Running the Ruby API Server

To run this basic API, you need to have Ruby installed on your system. The script initializes a WEBrick::HTTPServer instance, specifying the port (8080 in this case) on which it will listen for connections. The server.mount '/api', MyApi line maps all requests starting with /api to our MyApi handler. The trap('INT') { server.shutdown } ensures that the server can be gracefully shut down by pressing Ctrl+C. Finally, server.start begins the server's operation.

require 'webrick'
require 'json'

class MyApi < WEBrick::HTTPServlet::AbstractServlet
  def do_GET(request, response)
    # Handle GET request
    response.status = 200
    response['Content-Type'] = 'application/json'
    response.body = '{"message": "Hello, World!"}'
  end

  def do_POST(request, response)
    # Handle POST request
    begin
      request_body = JSON.parse(request.body)
      response.status = 200
      response['Content-Type'] = 'application/json'
      response.body = JSON.generate({message: "Received POST request with data", data: request_body})
    rescue JSON::ParserError
      response.status = 400
      response['Content-Type'] = 'application/json'
      response.body = JSON.generate({error: "Invalid JSON format"})
    end
  end

  def do_PUT(request, response)
    # Handle PUT request
    begin
      request_body = JSON.parse(request.body)
      response.status = 200
      response['Content-Type'] = 'application/json'
      response.body = JSON.generate({message: "Received PUT request with data", data: request_body})
    rescue JSON::ParserError
      response.status = 400
      response['Content-Type'] = 'application/json'
      response.body = JSON.generate({error: "Invalid JSON format"})
    end
  end

  def do_DELETE(request, response)
    # Handle DELETE request
    response.status = 200
    response['Content-Type'] = 'application/json'
    response.body = JSON.generate({message: "Received DELETE request"})
  end

end

server = WEBrick::HTTPServer.new(Port: 8080)
server.mount '/api', MyApi
trap('INT') { server.shutdown }
puts "Server started on http://localhost:8080/api"
server.start

Further Learning and Resources

To deepen your understanding of API development in Ruby, consider exploring: