Search code examples
jsoncrystal-langkemal

Get JSON in POST in kemal


What I want is a POST request in kemal where the body has a certain number of keys/values that I want to access and then an arbitrary JSON Object that I just want to stringify and pass on and later parse back to JSON.

My problem is that I apparently can't get the types right. Think of a potential JSON body like this:

{
  "endpoint": "http://example.com",
  "interval": 500,
  "payload": {
      "something": "else",
      "more": {
          "embedded": 1
      }
  }
}

Now what I've been trying to do is the following:

require "kemal"

post "/schedule" do |env|
  endpoint = env.params.json["endpoint"].as(String)
  interval = env.params.json["interval"].as(Int64)
  payload = String.from_json(env.params.json["payload"].as(JSON::Any))

  # ... move things along

  env.response.content_type = "application/json"
  { id: id }.to_json
end

Kemal.run

Now apparently what I seem to be getting when accessing "payload" is something of type Hash(String, JSON::Type), which confuses me a bit.

Any ideas how I'd be able to just get a sub-JSON from the request body, transform it to String and back to JSON?


Solution

  • Updated: payload is a type of JSON::Type. Casting and then calling .to_json does the trick.

    require "kemal"
    
    post "/schedule" do |env|
      endpoint = env.params.json["endpoint"].as(String)
      interval = env.params.json["interval"].as(Int64)
      payload = env.params.json["payload"].as(JSON::Type)
      env.response.content_type = "application/json"
      payload.to_json
    end
    
    Kemal.run