HTTP status codes are very much important in the restful web service and we should use appropriate status code from the server. HTTP provides response codes to inform clients of the status of their request. Use them carefully!
It’s very much essential to understand HTTP status codes for every developer. Don’t return a 200 response code every time, even in case of an error, it means, don’t use 200 Ok , if something is wrong. You can visit rest API example with different stacks as:
- Spring Restful Webservice example with Maven and Tomcat
- JAX-RS Jersey Rest service with XML+ Maven + Tomcat
- JAX-RS Jersey Rest service with JSON + Maven + Tomcat
1. HTTP status Codes overview
These are the Series status codes for HTTP response:
- HTTP Codes 1XX: for Informational
- HTTP Codes 2XX: for Success
- HTTP Codes 3XX: for redirection
- HTTP Codes 4XX: for Client side error code
- HTTP Codes 5XX: for Server side error code
I tried to brief with one or two error code for each section, with example
2. 2xx – HTTP Success codes for Success
- 200 – OK, this should be used when all goes well , it means if request executed successfully without any exception.
- 201 – Created, this should be used when a new resource has been created. Location header contains the address of the new resource.
- 202 – Accepted, a clients request is pending and will be completed later. Location header contains the expected address of the new resource, so it can be checked later.
2. 3xx – HTTP status codes for Redirection codes
- 301 – Moved Permanently, the API has moved a resource in response to the request, or an old resource is requested. Location cont
ains the new URI.
- 302 – Moved temporarily.
- 304 – Not Modified, the client already has this data, used when the client provided a If-Modified-Since header and the data hasn’t been modified. Date header is required, ETag and Content-Location should be same as a 200, Expires, Cache-Control and Vary are required if they’ve changed since last sent.
3. 4xx HTTP Status Code for Client side error
- 400 – Bad Request, there is a client-side problem, the document in the entity-body should contain more info on the problem
- 401 – Unauthorized, wrong credentials provided, or no credentials provided, resource is not authorize to access.
- 404 – Not Found, no resource matches the requested URI, there is no reference to it on the server.
4. 5xx – HTTP status Cdoe for Server side error
HTTP 5xx status code is for server side error and developer use this when any exception occured at server end or server is unable to process the request.
- 500 – Internal Server Error, there is an error on the server
Happy learning for Http status code which developer use for every Rest API.