Avatar Edgar González

  • Random
  • Archive
  • RSS

How to return a real empty response in Rails

I’m building a JSON API using rails. In several places I only need to send a 200 http code, without response body.

So, I used the head method:

head :ok

But this returns a response body with one blank character, this single space body causes the mobile client to fail (parse error). Below the response (notice the Content-Length):

HTTP/1.1 200 OK
Server: nginx/0.7.67
Date: Tue, 06 Sep 2011 14:13:55 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Piictu_version: 1.0.14
Cache-Control: no-cache
Content-Length: 1
X-Ua-Compatible: IE=Edge,chrome=1
X-Runtime: 0.273965

So, I created a render_ok method to use instead of head:

def render_ok
  response.headers['Cache-Control'] = 'no-cache'
  render json: ''
end

And now the response is:

HTTP/1.1 200 OK
Server: nginx/0.7.67
Date: Tue, 06 Sep 2011 16:14:05 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: no-cache
Etag: "d41d8cd98f00b204e9800998ecf8427e"
Piictu_version: 1.0.14
X-Ua-Compatible: IE=Edge,chrome=1
X-Runtime: 0.224352

Now the Content-Length header is not present :). I use render json: '', because I want the Content-Type to be application/json, but you can use render text: '' too.

    • #rails
    • #rails3
    • #json
  • 9 months ago
  • 6
  • Comments
  • Permalink
  • Share
    Tweet

6 Notes/ Hide

  1. foundationex liked this
  2. francesuy56 liked this
  3. gemfury liked this
  4. edgar posted this

Recent comments

Blog comments powered by Disqus
← Previous • Next →

Portrait/Logo

About

When I'm not spending time with Jessica and my kids, I build web applications. Rails developer, believer of Agile Development and Lean startups. NoSQL enthusiast.
CTO and Lord of the API at Piictu

Me, Elsewhere

  • @edgar on Twitter
  • Facebook Profile
  • edgargonzaleznetve on Youtube
  • egg on Flickr
  • edgar on Foursquare
  • My Skype Info
  • Linkedin Profile
  • edgar on github

Twitter

loading tweets…

  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr