RESTful Rails. Part I

Share this article

RESTful Rails have been a a much debated part of the Rails core, since the original restful_rails plugin was merged in to core just over a year ago. But with the improvements that have been made in Rails 2.0, they are here to stay, so it is important to understand what they are, how they work and when to (and when NOT to) use them. This is actually a pretty big topic, and I think it is worth while giving you some background first, so I’ll split the post in twain – Part I is theoretical, Part II is practical. So get your network protocol hats on, and get ready to learn about the inner workings of the language of the web.

REST vs. CRUD

Where would the web be with out acronyms? REST stands for REpresentational State Transfer and describes resources (in our case URLs) on which we can perform actions. CRUD
, which stands for Create, Read, Update, Delete, are the actions that we perform. Although, in Rails, REST and CRUD are bestest buddies, the two can work fine on their own. In fact, every time you have written a backend system that allows you to add, edit and delete items from the database, and a frontend that allows you to view those items, you have been working with CRUD.

HTTP Verbs

Any web developer who has had to deal with form data would be aware of the GET and POST methods. The former will submit data back to the server via a query string that looks something like this ?key2=value2&key2=value2 and the latter sends the data via HTTP headers. What you might not realise is that every time you are load a page (that isn’t a form of type POST) you are making a GET request. So when you clicked the link in your RSS reader that bought you here, you made a GET request. There are two other verbs that you might not have heard of because browsers don’t support them: PUT and DELETE. The delete action is obvious – if instructs the server to delete something. The PUT instruction is a little bit more cryptic – it is the same as POST action from the point of view that is sends data via headers, but it is designed to modify something (It also should create a new object if the object doesn’t already exist, but Rails ignores this minor technically). The more astute of you may have noticed that GET sounds a lot like READ, POST looks like CREATE, PUT is the same as UPDATE and DELETE is DELETE. If you did, move straight to the head of the class – this is exactly the correlation that Rails uses when working with RESTful rails.

HTTP Response codes

Everyone knows that if you try to access a page that doesn’t exist, the server will throw you back 404 Page not Found, or if you mess up your rails code, you will get a 500 Application Error
. These are response codes that the server sends back to let your browser know what is going on. Anything between 200-299 means the request was a success, 300-399 means the request was ok, but you need to do something else, 400-499 is an error and 500-599 is a really bad error. Just as there are verbs to match RESTful requests, there are response codes that correspond to RESTful responses.
200 OK
You will get from a GET, PUT or a DELETE request. It means that the request checked out and the appropriate action has been taken
201 Created
Notifies you that the POST command successfully created the posted object.
404 Not found
Means the request resource wasn’t found. You can get this from a GET, PUT or DELETE.
406 Not Acceptable
The verb isn’t allowed at the resources you reqested (More on this next part)
500 Internal Server Error
Something went horribly wrong

Resources

You would be used to seeing Rails URLs that look something like /posts/view/2 – which roughly translates to “Please let me view the post with the id number 2”. RESTful resources are very similar, in that they have a controller and (maybe) and id. What they generally don’t have is an action, because it is inherent in the HTTP verb. To make this work, the Rails team have defined a number of special methods in the controllers that define resources – in this case posts (the .xml bit will become clear in the next part).
MethodResourceVerbExplanation
index/posts.xmlGETReturns all items
show/posts/1.xmlGETReturn a single item with id = 1
create/posts.xmlPOSTCreate an item
update/posts/1.xmlPUTUpdate item with id = 1
delete/posts/1.xmlDELETEDelete item with id = 1
In reality, you can define additional actions (You can’t make every web site fit this model), and I will go through these in my next post. So, in the next part, we will look at how to create a RESTful rails project and how to wire everything up. Until then…

Frequently Asked Questions about RESTful Rails

What is the difference between RESTful and non-RESTful Rails?

RESTful Rails is a design pattern that follows the principles of Representational State Transfer (REST). It emphasizes a stateless client-server communication model, where each HTTP request from the client contains all the information needed to perform the operation. Non-RESTful Rails, on the other hand, may not adhere to these principles and could involve different methods of data transfer and communication.

How do I create a RESTful API with Rails?

Creating a RESTful API with Rails involves several steps. First, you need to set up a new Rails application with the –api flag. Then, you need to create a new resource with the Rails generate command. This will create a new controller and model for your resource. You can then define the routes for your resource in the routes.rb file. Finally, you can implement the actions in your controller to handle the different HTTP requests.

How do I test a RESTful API in Rails?

Rails provides several tools for testing RESTful APIs. You can use the built-in test framework, or you can use external libraries like RSpec and Factory Bot. To test a RESTful API, you would typically send HTTP requests to the API endpoints and then check the response for the expected data and status codes.

How do I secure a RESTful API in Rails?

Securing a RESTful API in Rails can involve several strategies. You can use token-based authentication, where the client sends a token in the HTTP header with each request. You can also use session-based authentication, where the server creates a session for the client after successful login. Additionally, you can use HTTPS to encrypt the data in transit between the client and the server.

How do I handle errors in a RESTful API in Rails?

Handling errors in a RESTful API in Rails typically involves returning appropriate HTTP status codes and error messages. For example, if a client sends a request for a resource that does not exist, you could return a 404 status code with a message indicating that the resource was not found. Rails provides several methods for handling errors, including the rescue_from method, which allows you to define custom error handling.

How do I version a RESTful API in Rails?

Versioning a RESTful API in Rails can be done in several ways. One common method is to include the version number in the URL of the API. Another method is to use HTTP headers to specify the version. This allows clients to specify the version of the API they wish to use with each request.

How do I paginate results in a RESTful API in Rails?

Paginating results in a RESTful API in Rails can be done using the Kaminari or Will Paginate gems. These gems provide methods for specifying the number of results per page and the current page number. The paginated results can then be returned in the response body along with metadata about the total number of results and pages.

How do I handle file uploads in a RESTful API in Rails?

Handling file uploads in a RESTful API in Rails can be done using the Active Storage framework. This allows you to attach files to Active Record objects and store them on a variety of cloud storage services. The uploaded files can then be accessed via a URL that is returned in the API response.

How do I implement search functionality in a RESTful API in Rails?

Implementing search functionality in a RESTful API in Rails can be done using the Ransack gem. This gem provides a simple and flexible way to build search forms and allows you to search your data using a variety of conditions.

How do I deploy a RESTful API in Rails?

Deploying a RESTful API in Rails can be done using a variety of platforms, including Heroku, AWS, and Google Cloud Platform. These platforms provide tools for managing and scaling your application, as well as monitoring its performance and handling errors.

Myles EftosMyles Eftos
View Author

Myles a Perth-based web developer who has worked in all the major web languages, his weapon of choice being Ruby on Rails—although he’s found himself doing more and more front-end development in JavaScript, HTML, and CSS.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week