Question

I'm creating a restful API for my app in Rails 4. I took a look at so many tutorials on that theme but in general they are all limited to creating a CRUD (create read update delete) API. That's easy and I already did that. But now i need to implement custom API endpoints behind which I perform various data processing. How can I do that in a right way? Where can I find information on the approach to building beautiful and relatively complex restful apis (like Foursquare API) in Ruby on Rails? Maybe there are real life open source examples?

Was it helpful?

Solution

A useful way of thinking about a RESTful API architecture is to think in terms of "nouns rather than verbs". REST is all about resources and resources should be nouns (e.g. a user or an event) rather than verbs (e.g. calculate or process).

To apply that to your problem of calculating the average number of participants in your events table, we have to think about what noun would represent that as a resource. It sounds like what you are getting at is some sort of report. This report would contain statistics such as the average number of participants as well as any other statistics that you might want to calculate down the road.

Your route might look something like this:

# singular resource
resource :events_report, only: [:show]

This will result in the following endpoint: /events_report which could return an EventsReport resource containing the result of all the processing you might want to do. This resource could be calculated on-the-fly (i.e. in the controller) or it could be pre-processed and stored in an ActiveRecord model.

The key to a good architecture is to not think of your endpoints as verbs (e.g. average) but as nouns (e.g. report) instead.

A good resource to check out would be the Art of Rails book, specifically Chapter 6. - Resources and REST.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top