Skip to content

Crystal HTTP Server — Building Web APIs with the Standard Library

DodaTech Updated 2026-06-29 1 min read

In this tutorial, you will learn about Crystal HTTP Server. We cover key concepts, practical examples, and best practices to help you master this topic.

Crystal's standard library includes a fast HTTP server and client. You can build production-ready web APIs without external frameworks.

HTTP Server

require "http/server"

server = HTTP::Server.new do |context|
  context.response.content_type = "text/plain"
  context.response.print "Hello, Crystal!"
end

address = server.bind_tcp 8080
puts "Listening on http://localhost:8080"
server.listen

Routing

require "http/server"

server = HTTP::Server.new do |context|
  request = context.request
  response = context.response

  case request.method
  when "GET"
    case request.path
    when "/"
      response.print "Home"
    when "/api/users"
      response.print "Users"
    else
      response.status = :not_found
      response.print "Not found"
    end
  when "POST"
    body = request.body.try(&.gets_to_end) || ""
    response.print "Received: #{body}"
  end
end

JSON API

require "http/server"
require "json"

server = HTTP::Server.new do |context|
  context.response.content_type = "application/json"
  context.response.print({status: "ok", version: 1}.to_json)
end

server.bind_tcp 3000
server.listen

HTTP Client

require "http/client"

response = HTTP::Client.get("https://api.example.com/users")
puts response.status_code
puts response.body

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro