Neeraj Neeraj -4 years ago 158
reST (reStructuredText) Question

HTTP status code in GET Method of REST api design

I am learning about the best practices involved in REST API design and wrote a function which handles the GET /cities HTTP/1.1 query.

This function contains cities which is a struct array that holds the cityname, citycode of multiple cities.

Below is the code

func FindCitiesHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json;charset=UTF-8")

if len(cities) == 0 {

if err := json.NewEncoder(w).Encode(cities); err != nil {
/* what to do here? */



Now when I started thinking about the possible outcomes of this function. I found these situations.

  1. It returns all the cities properly as JSON response successfully. So I return 200 http status.

  2. The list of cities is empty. So there is nothing to return. So I return 404 (resource not found)

  3. It is about to return JSON response of all cities, but something gone wrong during JSON encoding. Now I am confused here, how do I deal with this situation.

I mean how do you convey message properly to user, if

  1. If your business/application logic had some error/exception.

  2. If data access logic found some issues. (say connection to database is not reachable)

Could you guys please help me to suggest best practices you followed in these situations?

Answer Source
  1. 200 is correct
  2. 404 is probably not correct; A list of cities can be empty, and still exist. (Think: A 0-length array is still an array.) You should probably return 200. You would only return 404 if the list of cities doesn't exist on your server (in other words, that should probably never happen with your API).
  3. If you experience an internal server error, such as with marshaling JSON, you should return an Internal Server Error, status 500.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download