From eb546315d1a9c5b7c265dbbac48b1c88b334022a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fatih=20Kadir=20Ak=C4=B1n?= Date: Fri, 4 Dec 2015 13:52:39 +0200 Subject: [PATCH] Create http-requests.md --- docs/http-requests.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 docs/http-requests.md diff --git a/docs/http-requests.md b/docs/http-requests.md new file mode 100644 index 0000000..942bee1 --- /dev/null +++ b/docs/http-requests.md @@ -0,0 +1,40 @@ +# HTTP Requests + +You should use `env` variable to handle HTTP params. For both `get` and `post` (and others) methods, you should use `env` object. + +```ruby +# Matches /hello/kemal + get "/hello/:name" do |env| + name = env.params["name"] + "Hello back to #{name}" + end + + # Matches /resize?width=200&height=200 + get "/resize" do |env| + width = env.params["width"] + height = env.params["height"] + end + + # Easily access JSON payload from the params. + # The request content type needs to be application/json + # The payload + # {"name": "Serdar", "likes": ["Ruby", "Crystal"]} + post "/json_params" do |env| + name = env.params["name"] as String + likes = env.params["likes"] as Array + "#{name} likes #{likes.each.join(',')}" + end + + # Set the content as application/json and return JSON + get "/user.json" do |env| + kemal = {name: "Kemal", language: "Crystal"} + env.content_type = "application/json" + kemal.to_json + end + + # Add headers to your response + get "/headers" do |env| + env.add_header "Accept-Language", "tr" + env.add_header "Authorization", "Token 12345" + end +```