How to create a REST API for a Ruby application?

前端 未结 4 1051
臣服心动
臣服心动 2021-01-31 00:47

I would like to know how to provide a Ruby application with a REST API. I could code something based on Ruby\'s TCPServer API, but that seems a bit low-level. Do you think it wo

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 01:17

    There are several layers involved when desiging a RESTful API, and at each layer there are several valid approaches.

    TCPServer is indeed very low level, since you would have to implement the HTTP protocol yourself, which is not recommended.

    One step up would be Rack, which takes care of all the low-level HTTP details. This is what all Ruby web frameworks like Rails, Sinatra or Ramaze use under the hood. It also assures that your application works on various application servers, like Passenger, Thin or Unicorn.

    But even Rack is still low level, it gives you HTTP, but higher level frameworks take the boilerplate out of typical web programming. For an API you could look at a minimal framework like Sinatra, or a framework specifically designed for APIs like Grape or Rails::API. These will already assume a RESTful style API, so you should find them to be a natural fit.

    Typical RESTful APIs are characterized by having resources identified by guessable (convention driven) URLs, and operations on those based on HTTP methods (verbs) like GET, POST, PUT, DELETE and PATCH. To truly embrace the spirit of REST as it was described by Roy Fielding however, you could move towards a more full "Hypermedia" API. The most visible difference is that responses are more self-contained. They are of well-defined media types (defined by yourself or by existing specs) containing links to related resources, rather than merely numerical ids. Similarly responses contain templates/forms describing the operations that can be performed. (There is more to it, but on the surface level that's what you will notice.)

    This makes the API more discoverable, both by humans and machines, and it allows for a greater freedom in evolving the API. There could be a performance drawback, since a client typically would need to do more requests to achieve the same thing, but this can be prevented by well thought out design and caching. Garner is specifically made to provide easy server-side caching.

    You could define your own media types that suit your application, commonly on top of JSON or XML, or you could look at existing specifications, notably Collection+JSON, HAL and JSON-API. It seems at the moment HAL has the biggest traction, with several libraries available on a variety of platforms.

    There is seemingly not a whole lot happening around JSON-API, but two signifacnt projects, ActiveModel::Serializers and Ember-data, are both adopting (and at the same time, developing) this format, which means it could become a popular choice in the Ruby/Rails world.

    Edit : typo

提交回复
热议问题