Minimum configuration of Ruby REST-like API framework "grape" (with RSpec / Heroku compatible)

The minimum configuration to create an API server that returns {" response ":" pong "} with GET/ping using the Ruby REST-like API framework" grape ".

File/directory structure

.
├── Gemfile
├── Procfile
├── config.ru
├── api.rb
└── spec
    ├── spec_helper.rb
    └── api_spec.rb

Unit test

bundle exec rspec spec/api_spec.rb

Local development

bundle exec rackup
##Or
heroku local:start

File description

Gemfile

After creating with bundle init, do the following:

--Specify Ruby version (for Heroku) --Specify grape, rspec, puma --rack-test is for unit tests (RSpec)

Gemfile


# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

ruby "~> 3.0.0"

gem "grape"
gem "rspec"
gem "puma"

group :development do
  gem "rack-test"
end

Procfile

Procfile is for Heroku. Not required if you don't use Heroku.

Procfile


web: bundle exec rackup config.ru -p $PORT

config.ru

For rackup.

config.ru


require_relative File.join("api")
run APIserver

api.rb

API body.

api.rb


require "grape"

class APIserver < Grape::API
  format :json

  get "/ping" do
    {"response": "pong"}
  end
end

spec/spec_helper.rb

For RSpec. require_relative is the same as config.ru.

require" rack/test " The following is a magical target, as described in grape/RSpec. You need to ensure that app returns an instance of the API.

spec/spec_helper.rb


require_relative File.join("..", "api")

require "rack/test"
include Rack::Test::Methods
def app
  APIserver
end

spec/api_spec.rb

Unit test body.

spec/api_spec.rb


require "spec_helper"

context "GET ping" do
  it "return pong" do
    get "/ping"
    expect(last_response.status).to eq(200)
    expect(JSON.parse(last_response.body)).to eq({"response" => "pong"})
  end
end

Future expansion points

The entry point for rackup (web server) is config.ru, and the entry point for RSpec (unit test) is spec_helper.rb. Let's concentrate (or standardize) require etc. here.

If you want to implement the API data structure, you can use grape-entity. Nested 1: N structures can also be implemented. Representing one-to-many data structures using Grape :: Entity in RESTful API

You can use rspec-json_matcher to validate complex JSON. See Rspec-json_matcher gives you the freedom to validate JSON for examples of complex cases.

EoT

Recommended Posts

Minimum configuration of Ruby REST-like API framework "grape" (with RSpec / Heroku compatible)
Minimum configuration sample of RESTful API in Jersey + Spring Framework
Try Hello World with the minimum configuration of Heroku Java spring-boot
Compatible with Android 10 (API 29)
Understand code coverage with Rspec, the Ruby on Rails test framework