Skip to main content

REST response

As one can expect, a request is usually followed by a response.

Depending on the request made, the response can be in the form of a returned dataset. For example, following a GET-request for time entries, you could expect the response object to contain an array of time-entries. Following a POST-request to add a time-entry to a database, you could expect the response to be "Success" or "Failure".

The above is however a slightly simplified version of reality..

First, the response object returned by the RESTful API can come in different formats. Often the response object is in JSON format, yet it's not 'sent' in this format. This means that we first have to apply the .json() method to our response object within our React component:

const response = await fetch("http://localhost:3004/time-entries", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});

const formattedResponse = response.json();

Second, the code gods won't always be on your side... The degree of 'success' of your request is portrayed by the "status code" that accompanies your response object. Remember the infamous "Error 404"? That's an example of a response object with status code "404", which is returned when your request returns something that is "not found". Status code "200" means "OK", or in other words: a successful request.

As such, after you .json() your response. Your response object will look somewhat like this in case of success:

{
"status": "200",
"data": {
// *** Application-specific data would go here. ***
},
"message": *** null / or optional success message ***
}

and in case of a failed request somewhat like this:

{
"status": "404",
"data": {}, // *** null or optional error payload ***
"message": "Not found"
}