Git Product home page Git Product logo

api_versioner's Introduction

API Versioner

API Versioner is a tiny focused gem that provides support for semantic versioning to API apps. The idea is as follows:

  • Backend has its current API version that it exposes in the X-API-Server-Version response header by default
  • Client requests a certain API version by sending it in the X-API-Client-Version request header by default
  • Before processing the request, backend checks the requested version against the current version using some policy and terminates with an error if the version is unsupported.

All moving parts (headers names, the policy and the handler) are configurable.

Middlewares

During initialization if the gem sees it's used in a Rails app, it installs two middlewares:

  • ApiVersioner::ServerVersionMiddleware places the current version in the response header (defaults to X-API-Server-Version). The header name and the current version is configurable.
  • ApiVersioner::ClientVersionMiddleware analyzes the version in the said request header (defaults to X-API-Client-Version) and checks it against the current server version using a specified policy.

Installation

Add this line to your application's Gemfile:

gem 'api_versioner'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install versioner

Usage

# config/initializers/versioner.rb

ApiVersioner.configure do |config|
  # Current version of the application
  config.current_version = '1.2.3'

  # The name of the header to set the current server API version
  # Default: 'X-API-Server-Version'
  config.server_version_header = 'X-API-Server-Version'

  # The header to look for the API version required by the client
  # Default: 'X-API-Client-Version'
  config.client_version_header = 'X-API-Client-Version'

  # A callable object to check version policy. It's called with current server version
  # and the requested version from the request header (`client_version_header`).
  # If the requested version is unsupported, the `ApiVersioner::UnsupportedVersion` error should be raised.
  config.version_policy = ApiVersioner::DefaultPolicy.new

  # A callable object to handle the `ApiVersioner::UnsupportedVersion` error in a way
  # specific to your application. It's called with the error and the configuration.
  # The default implementation renders JSON like below and returns it with error code 400.
  config.unsupported_version_handler = ApiVersioner::DefaultHandler.new
end

Policy

A policy is a callable object with two arguments, like below:

class CustomPolicy
  def call(current_version, requested_version)
    raise ApiVersioner::UnsupportedVersion, "This version is ..." if some_condition?
  end
end

A policy should raise the ApiVersioner::UnsupportedVersion error if the requested version is unsupported.

The default implementation (ApiVersioner::DefaultPolicy) passes for:

  • unspecified versions
  • equal versions
  • requested versions that are lower than current on minor and/or patch levels

Raises errors for:

  • requested versions that are lower than current on major level
  • requested versions that are higher than current

UnsupportedVersion error

ApiVersioner::UnsupportedVersion error has reason field that is not initialized by default. You can initialize it with your own value as necessary. This value is returned in the error meta-section by the ApiVersioner::DefaultHandler as shown in the next section.

Handler

The handler is a callable object that generates the response when an unsupported version is detected.

class CustomHandler
  def call(error, config)
    [200, {}, ['Version error']]
  end
end

The default implementation (ApiVersioner::DefaultHandler):

  • Returns status 400 (Bad Request)
  • Renders JSON content as follows:
{
  "errors": [
    {
      "title": "Error message ...",
      "status": 400,
      "code": "UNSUPPORTED_VERSION",
      "meta": {
        "reason": <error.reason>
      }
    }
  ]
}

Default policy reason codes are:

  • TOO_LOW - major number of the requested version is lower than current
  • TOO_HIGH - requested version is higher than current on any level

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/versioner. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

api_versioner's People

Contributors

aglushkov avatar alg avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.