27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Versioning an API<br />

That completes everything you need to do for rate limiting in your API. Before you<br />

make a commit, run all the specs with the rake spec to see if the API is still working:<br />

56 examples, 0 failures, 18 pending<br />

All good! You can commit this now:<br />

git add .<br />

git commit -m "Added rate limiting to the V1 API"<br />

git push<br />

You’ve implemented a way to stop people from making too many requests to your API,<br />

which will possibly stop your application from being overloaded due to excessive API<br />

requests. Next, we look at how you can implement versioning in your API.<br />

13.4 Versioning an API<br />

At the beginning of this chapter, we discussed how all your API routes would be under<br />

the /api/v1/ namespace. This was because you wanted to provide a predictable outcome<br />

of the requests to the URLs. If you go changing URLs to provide extra data or to<br />

take away data, some API clients may malfunction. So when you want to make changes<br />

to your API, you group them all up into logical versions.<br />

With this separation, you can provide a link, such as /api/v1/projects.json, which<br />

will return the attributes you’re already familiar with, as well as another path for the<br />

next version. This second version’s path will be /api/v2/projects.json, and the difference<br />

between the two is that you’ll change the name field to be called title instead.<br />

Although this is potentially a trivial example, 16 it’s a great case to show off how to<br />

make two API versions different.<br />

13.4.1 Creating a new version<br />

To begin the versioning process, copy these routes from config/routes.rb in your<br />

application:<br />

namespace :api do<br />

namespace :v1 do<br />

resources :projects<br />

end<br />

end<br />

And place them beneath, renaming v1 to v2:<br />

namespace :api do<br />

namespace :v2 do<br />

resources :projects<br />

end<br />

end<br />

Now you’ll need to create a new app/controllers/api/v2 directory, which you can do<br />

by copying app/controllers/api/v1 into that location. You’ve now got version 2 of<br />

16 Also a tiny fraction slower than v1, given you’ll be calling a method from within another method rather<br />

renaming it.<br />

381

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!