status codes 101

18 June 2009 | 6:47 pm by codeboxer

Ah, the old http status code. Very nice. I recently built my first pro-grade web service and had some problems figuring out the status codes. Here are some tips from my friend happyfrenchy2:

Usually I write my rest service so that a problem with the parameters (wrong ID, not enough params, etc) returns a 400 (bad request), a auth failure (wrong signature) returns a 403 (forbidden) and an internal problem (couldn’t access DB for instance) returns a 503 (server error). Return code 500 should be when the error happens before your code was even reached (like the server or web-server is down).

Very helpful. This is what that looks like, in the create method of the /installs web service:

  def create

    respond_to do |format|
      format.xml {
        install = OnInstall.new do |i|
          i.ip_address = request.remote_ip
          i.mac_address = params[:mac_address]
          i.on_dvd_id = params[:on_dvd_id].to_i
          i.on_dvd_number = params[:on_dvd_number]
          i.on_dvd_set_id = params[:on_dvd_set_id].to_i
          i.on_game_id = params[:on_game_id].to_i
        end
        ts_param = params[:redacted]
        hash_to_match = params[:redacted]
        begin
          #FK validations
          test = OnDvd.find(install.on_dvd_id)
          test = OnDvdSet.find(install.on_dvd_set_id)
          test = OnGame.find(install.on_game_id)
          
          #validate md5 hash
          live_matcher = "redacted"
          digest = Digest::MD5.hexdigest(live_matcher)
          if digest.upcase == hash_to_match.upcase
            if install.save
              headers['location'] = on_install_path(install.id)
              render :nothing => true, :status => "201 Created"
            else
              render :xml => install.errors.to_xml, :status => "400 Bad Request"
            end
          else
            render :xml => "Your s param hash did not match the POST fields.", :status => "403 Forbidden"
          end
          
        rescue Exception => e 
          render :xml => e.message, :status => "503 Server Error"
        end
        }
      format.html {if current_user == :false then redirect_to home_url else super end}
    end
  end



Recommend Me




My Site Links

Screenshots are featured above. If you visit gmgpulse, you may login as demo/demo.

Rockstar Television


© 2008-10 Krister Axel and codeboxer.com