{"id":15653192,"url":"https://github.com/pat/sliver","last_synced_at":"2025-04-15T11:53:46.091Z","repository":{"id":16646543,"uuid":"19401900","full_name":"pat/sliver","owner":"pat","description":"A super simple, extendable Rack API.","archived":false,"fork":false,"pushed_at":"2024-03-08T11:08:30.000Z","size":51,"stargazers_count":29,"open_issues_count":0,"forks_count":2,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-03-28T19:45:10.334Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pat.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-05-03T11:47:14.000Z","updated_at":"2024-12-10T09:59:08.000Z","dependencies_parsed_at":"2024-10-03T12:44:59.462Z","dependency_job_id":"749befce-d06e-460b-ad64-5209deeecbf0","html_url":"https://github.com/pat/sliver","commit_stats":null,"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pat%2Fsliver","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pat%2Fsliver/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pat%2Fsliver/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pat%2Fsliver/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pat","download_url":"https://codeload.github.com/pat/sliver/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249067759,"owners_count":21207395,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-03T12:44:55.466Z","updated_at":"2025-04-15T11:53:46.065Z","avatar_url":"https://github.com/pat.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Sliver\n\nA super simple, extendable Rack API.\n\n[![Build Status](https://travis-ci.org/pat/sliver.svg?branch=master)](https://travis-ci.org/pat/sliver)\n[![Code Climate](https://codeclimate.com/github/pat/sliver.svg)](https://codeclimate.com/github/pat/sliver)\n[![Gem Version](https://badge.fury.io/rb/sliver.svg)](http://badge.fury.io/rb/sliver)\n\n## Why?\n\nRuby doesn't lack for web frameworks, especially ones focused on APIs, but Sliver is a little different from others I've come across.\n\n* It focuses on one class per endpoint, for increased Single Responsibility Principle friendliness.\n* Separate classes allows for better code organisation, instead of everything in one file.\n* It's a pretty small layer on top of Rack, which is the only dependency, which keeps things light and fast.\n* Guards and processors provide some structures for managing authentication, JSON responses and other common behaviours across actions (similar to Rails before_action filters).\n\n## Installation\n\nAdd it to your Gemfile like any other gem, or install it manually.\n\n```ruby\ngem 'sliver', '~\u003e 0.2.5'\n```\n\n## Usage\n\nAt its most basic level, Sliver is a simple routing engine to other Rack endpoints. You can map out a bunch of routes (with the HTTP method and the path), and the corresponding endpoints for requests that come in on those routes.\n\n### Lambda Endpoints\n\nHere's an example using lambdas, where the responses must match Rack's expected output (an array with three items: status code, headers, and body).\n\n```ruby\napp = Sliver::API.new do |api|\n  api.connect :get, '/', lambda { |environment|\n    [200, {}, ['How dare the Premier ignore my invitations?']]\n  }\n\n  api.connect :post '/hits', lambda { |environment|\n    HitMachine.create! Rack::Request.new(environment).params[:hit]\n\n    [200, {}, [\"He'll have to go!\"]]\n  }\nend\n```\n\n### Sliver::Action Endpoints\n\nHowever, it can be nice to encapsulate each endpoint in its own class - to keep responsibilities clean and concise. Sliver provides a module `Sliver::Action` which makes this approach reasonably simple, with helper methods to the Rack environment and a `response` object, which can have `status`, `headers` and `body` set (which is automatically translated into the Rack response).\n\n```ruby\napp = Sliver::API.new do |api|\n  api.connect :get, '/changes', ChangesAction\nend\n\nclass ChangesAction\n  include Sliver::Action\n\n  def call\n    # This isn't a realistic implementation - just examples of how\n    # to interact with the provided variables.\n\n    # Change the status:\n    response.status = 404\n\n    # Add to the response headers:\n    response.headers['Content-Type'] = 'text/plain'\n\n    # Add a response body - let's provide an array, like Rack expects:\n    response.body = [\n      \"How dare the Premier ignore my invitations?\",\n      \"He'll have to go\",\n      \"So too the bunch he luncheons with\",\n      \"It's second on my list of things to do\"\n    ]\n\n    # Access the request environment:\n    self.environment\n\n    # Access to a Rack::Request object built from that environment:\n    self.request\n  end\nend\n```\n\n### Path Parameters\n\nMuch like Rails, you can have named parameters in your paths, which are available via `path_params` within your endpoint behaviour:\n\n```ruby\napp = Sliver::API.new do |api|\n  api.connect :get, '/changes/:id', ChangeAction\nend\n\nclass ChangeAction\n  include Sliver::Action\n\n  def call\n    change = Change.find path_params['id']\n\n    response.status = 200\n    response.body   = [\"Change: #{change.name}\"]\n  end\nend\n```\n\nIt's worth noting that unlike Rails, these values are not mixed into the standard `params` hash.\n\n### Guards\n\nSometimes you're going to have endpoints where you want to check certain things before getting into the core implementation: one example could be to check whether the request is made by an authenticated user. In Sliver, you can do this via Guards:\n\n```ruby\napp = Sliver::API.new do |api|\n  api.connect :get, '/changes/:id', ChangeAction\nend\n\nclass ChangeAction\n  include Sliver::Action\n\n  def self.guards\n    [AuthenticatedUserGuard]\n  end\n\n  def call\n    change = Change.find path_params['id']\n\n    response.status = 200\n    response.body   = [\"Change: #{change.name}\"]\n  end\n\n  def user\n    @user ||= User.find_by :key =\u003e request.env['Authentication']\n  end\nend\n\nclass AuthenticatedUserGuard \u003c Sliver::Hook\n  def continue?\n    action.user.present?\n  end\n\n  def respond\n    response.status = 401\n    response.body   = ['Unauthorised: valid session is required']\n  end\nend\n```\n\nGuards inheriting from `Sliver::Hook` just need to respond to `call`, and have access to `action` (your endpoint instance) and `response` (which will be turned into a proper Rack response).\n\nThey are set in the action via a class method (which must return an array of classes), and a guard instance must respond to two methods: `continue?` and `respond`. If `continue?` returns true, then the main action `call` method is used. Otherwise, it's skipped, and the guard's `respond` method needs to set the alternative response.\n\n### Processors\n\nProcessors are behaviours that happen after the endpoint logic has been performed. These are particularly useful for transforming the response, perhaps to JSON if your API is expected to always return JSON:\n\n```ruby\napp = Sliver::API.new do |api|\n  api.connect :get, '/changes/:id', ChangeAction\nend\n\nclass ChangeAction\n  include Sliver::Action\n\n  def self.processors\n    [JSONProcessor]\n  end\n\n  def call\n    change = Change.find path_params['id']\n\n    response.status = 200\n    response.body   = {:id =\u003e change.id, :name =\u003e change.name}\n  end\nend\n\nclass JSONProcessor \u003c Sliver::Hook\n  def call\n    response.body                    = [JSON.generate(response.body)]\n    response.headers['Content-Type'] = 'application/json'\n  end\nend\n```\n\nProcessors inheriting from `Sliver::Hook` just need to respond to `call`, and have access to `action` (your endpoint instance) and `response` (which will be turned into a proper Rack response).\n\n### Testing\n\nBecause your API is a Rack app, it can be tested using `rack-test`'s helper methods. Here's a quick example for RSpec:\n\n```ruby\ndescribe 'My API' do\n  include Rack::Test::Methods\n\n  let(:app) { MyApi.new }\n\n  it 'responds to GET requests' do\n    get '/'\n\n    expect(last_response.status).to eq(200)\n    expect(last_response.headers['Content-Type']).to eq('text/plain')\n    expect(last_response.body).to eq('foo')\n  end\nend\n```\n\n### Running via config.ru\n\nIt's pretty easy to run your Sliver API via a `config.ru` file:\n\n```ruby\nrequire 'rubygems'\nrequire 'bundler'\n\nBundler.setup :default\n$:.unshift File.dirname(__FILE__) + '/lib'\n\nrequire 'my_app'\n\nrun MyApp::API.new\n```\n\n### Running via Rails\n\nOf course, you can also run your API within the context of Rails by mounting it in your `config/routes.rb` file:\n\n```ruby\nMyRailsApp::Application.routes.draw do\n  mount Api::V1.new =\u003e '/api/v1'\nend\n```\n\nThere is also the [sliver-rails](https://github.com/pat/sliver-rails) gem which adds some nice extensions to Sliver with Rails in mind.\n\n## Contributing\n\nPlease note that this project now has a [Contributor Code of Conduct](http://contributor-covenant.org/version/1/0/0/). By participating in this project you agree to abide by its terms.\n\n1. Fork it ( https://github.com/pat/sliver/fork )\n2. Create your feature branch (`git checkout -b my-new-feature`)\n3. Commit your changes (`git commit -am 'Add some feature'`)\n4. Push to the branch (`git push origin my-new-feature`)\n5. Create a new Pull Request\n\n## Licence\n\nCopyright (c) 2014-2015, Sliver is developed and maintained by Pat Allan, and is\nreleased under the open MIT Licence.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpat%2Fsliver","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpat%2Fsliver","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpat%2Fsliver/lists"}