Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Demonstrate header handling. #18

Merged
merged 1 commit into from Jul 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -17,6 +17,7 @@ A [Grape](http://github.com/ruby-grape/grape) API mounted on Rack.
* [content_type](api/content_type.rb): an example that overrides the default `Content-Type` or returns data in both JSON and XML formats
* [upload_file](api/upload_file.rb): an example that demonstrates a file upload and download
* [entites](api/entities.rb): an example of using [grape-entity](https://github.com/ruby-grape/grape-entity)
* [headers](api/headers.rb): demonstrates header case-sensitive handling

See
---
Expand Down
21 changes: 21 additions & 0 deletions api/headers.rb
@@ -0,0 +1,21 @@
module Acme
class Headers < Grape::API
format :json

namespace :headers do
desc 'Returns a header value.'
params do
requires :key, type: String
end
get ':key' do
key = params[:key]
{ key => headers[key] }
end

desc 'Returns all headers.'
get do
headers
end
end
end
end
1 change: 1 addition & 0 deletions app/api.rb
Expand Up @@ -13,6 +13,7 @@ class API < Grape::API
mount ::Acme::ContentType
mount ::Acme::UploadFile
mount ::Acme::Entities::API
mount ::Acme::Headers
add_swagger_documentation api_version: 'v1'
end
end
44 changes: 44 additions & 0 deletions spec/api/headers_spec.rb
@@ -0,0 +1,44 @@
require 'spec_helper'

describe Acme::API do
include Rack::Test::Methods

def app
Acme::API
end

it 'returns all headers' do
get '/api/headers'
expect(JSON.parse(last_response.body)).to eq(
'Cookie' => '',
'Host' => 'example.org'
)
end

it 'returns a Host header' do
get '/api/headers/Host'
expect(JSON.parse(last_response.body)).to eq('Host' => 'example.org')
end

it 'headers are converted to pascal-case' do
get '/api/headers/Host'
expect(JSON.parse(last_response.body)).to eq('Host' => 'example.org')
end

it 'headers via Rack::Test API' do
header 'Reticulated-Spline', 42
get '/api/headers/Reticulated-Spline'
expect(JSON.parse(last_response.body)).to eq('Reticulated-Spline' => 42)
end

it 'headers via arg' do
get '/api/headers', nil,
'HTTP_RETICULATED_SPLINE' => 42,
'SOMETHING_ELSE' => 1
expect(JSON.parse(last_response.body)).to eq(
'Cookie' => '',
'Host' => 'example.org',
'Reticulated-Spline' => 42
)
end
end