Making a POST request to a Rails API Endpoint

Here's a rare super-technical blog post. I spent enough time struggling with this seemingly simple problem today, that I felt I should share the answer.

The problem: You're designing a REST API for your Rails app. You want to let people insert records in your application via a POST request. However they submit their POST request via their 3rd party application, and your app throws an InvalidAuthenticityToken exception. Why is this happening?

The background: Ruby on Rails stores an authenticity token for each session, and submits this token as a hidden form field in any POST request upon a form submission. It does this to authenticate that the request is actually coming as a form submission through the web site, as opposed to a random POST request generated from CURL or another tool. A 3rd party application developer certainly doesn't have a token assigned and therefore can't submit this via their API request.

The solution: Rails only checks for the authenticity token in the case of a form submission. If you submit your data as content-type application/xml or application/json, then the token is not required. As a result you can set the content type appropriately and encode your input parameters as either xml or json. See the below gist for a ruby example.

It was hard to find this solution via google. Anyone know a smoother solution? Does the API designer generally disable forgery protection in this scenario on POST endpoints for inserting data via an API? Let me know in the comments or on twitter @petkanics