Kemal Web Framework Documentation

repository·master·Indexed 26 days ago

https://github.com/kemalcr/kemal

A fast and simple web framework for the Crystal programming language used for building web applications and APIs. Features include a DSL for HTTP routing (get, post, put, patch, delete), JSON API support, WebSocket endpoints via the ws method, and a CLI for configuring host binding, ports, and SSL settings.

Tokens
629
Snippets
1
Records
3
Agent score
37%

What's inside Kemal

  1. Quick Start with Kemal

    master

    To get started with Kemal, ensure you have Crystal installed. Follow these steps to create a new application:

    1. Initialize a new Crystal app:
      crystal init app my-kemal-app
      cd my-kemal-app
    2. Add kemal to your shard.yml dependencies:
      dependencies:
        kemal:
          github: kemalcr/kemal
    3. Install dependencies and run the application:
      shards install
      crystal run src/my_kemal_app.cr
  2. Basic Routing, JSON APIs, and WebSockets in Kemal

    master

    Kemal provides a simple DSL for defining routes, handling JSON responses, and managing WebSocket connections.

    • Use get, post, put, patch, and delete for standard HTTP verbs.
    • Access the environment object (env) in route blocks to manipulate responses, such as setting the content_type.
    • Use ws to define WebSocket endpoints.
    • Call Kemal.run to start the server.
    require "kemal"
    
    # Basic route - responds to GET "http://localhost:3000/"
    get "/" do
      "Hello World!"
    end
    
    # JSON API example
    get "/api/status" do |env|
      env.response.content_type = "application/json"
      {"status": "ok"}.to_json
    end
    
    # WebSocket support
    ws "/chat" do |socket|
      socket.send "Hello from Kemal WebSocket!"
    end
    
    Kemal.run
  3. Use the Kemal CLI to configure host, port, and SSL

    master

    The Kemal CLI allows you to configure the server's host binding, port, and SSL settings via command-line arguments. These arguments override the default values set in Kemal.config.

    Available Flags

    FlagLong FlagDescription
    -b HOST--bind HOSTHost to bind (defaults to Kemal.config.host_binding)
    -p PORT--port PORTPort to listen for connections (defaults to Kemal.config.port)
    -s--sslEnables SSL
    --ssl-key-file FILESpecifies the SSL key file (required if --ssl is used)
    --ssl-cert-file FILESpecifies the SSL certificate file (required if --ssl is used)
    -h--helpShows this help

    SSL Requirements

    If you enable SSL using --ssl, you must also provide both a key file and a certificate file using --ssl-key-file and --ssl-cert-file. Failure to provide these will result in an error.