Activity 30: HTTP Status Codes | Aligan, Rhed N.

Activity 30: HTTP Status Codes | Aligan, Rhed N.

What is HTTP status codes?

  • HTTP status codes are numeric responses that have unique meaning response for the client. It’s a way for servers to let us know as a client or customer what happened after we make a request to them.

  • In a basic analogy, this is the response of server in our request and every numeric response has a different content or meaning so it can be able to understand the response in a numeric way used especially in RESTFUL APIs.

So, there are a different way to make the client or customer of what the feedback of their request. Let’s start.

  • 1xx (Informational)

    Indicates that the initial part of a request has been received, and the client should continue sending the rest of the request. But there’s no final response.

Example

If customer want to add to the menu image in the restaurant, he/she uploads but the server checks first if it can accept the file before the client sends the complete data, it’s like an initial information if their request is capable to response on their request. This scenario is commonly used to prevent the client from sending a large payload if the server might reject it due to size constraints or other conditions.

Using POST METHOD, the API endpoint for instances use are, https://example.com/api/upload-image so the initial response will be

HTTP/1.1 100 Continue

After receiving 100 continue, the clients have sent the file body or content.

  • 2xx (Success):

    • 200 OK: This is the most common success status code. It indicates that the request was successfully processed and that the response body contains the requested data. For example, a successful GET request will return a 200 OK.

Example

  • Using GET METHOD for instances, we want to get the information of user, the URL is like https://api.rhedaliganstore.com/users

    The status code will response of 200 OK if the request and response are succesful.

[
  {
    "id": 1,
    "name": "Jonalyn Nebril",
    "email": "jonalyn312@yahoo.com"
  },
  {
    "id": 2,
    "name": "Rhed ford White",
    "email": "rhed123@skype.com"
  }
]

In this explanation, the request was successful, and the response body contains the list of users of rhedaliganstore.

  • 201 Created: This code is used when a new resource has been successfully created as a result of the request. It is commonly used with POST requests, indicating that the resource has been created (for instance, when creating a new record in a database). The response may also include a Location header to indicate the URL of the newly created resource.

Example

Now using POST Method, you want to add new information like a new menu or new user in the server database. You create a URL like api.rhedaliganstore/users

The header Content-Type: application/json and Authorization: Bearer <your_token>

Adding information, Authorization Bearer Token is a type of authentication mechanism used to verify the identity of a user or service when making API requests. The token is often used in web applications and APIs to securely access protected resources.

{
  "name": "Alice Smith",
  "email": "alice@example.com"
}

This the new user will be added in the server and when the status code responde of 201 CREATED, the list of user show with the unique id

{
  "id": 3,
  "name": "Alice Smith",
  "email": "alice@example.com"
}
//Anticipate there's a first two user listed so the ID is 3.

The header will be located https://api.example.com/users/3

Added more, the new user was successfully created. The response body includes the new user’s information, and the Location header points to the newly created resource.

  • 204 No Content: means that the request was successful, but there is no content to return in the response body. It's often used for requests that don't require a response body, like a DELETE request where a resource has been deleted successfully, or a PUT request that updates an existing resource without needing to send any content back.

Example

Using DELETE METHOD, now after adding the new information we want now to delete the user. The URL will be https://api.rhedaliganstore.com/users/3

The response status code would be 204 No Content. So, in this explanation The request was successful, and the user with ID 3 has been deleted. Since there is no need to return content in the body, the response has no body, but the 204 No Content status code confirms the success.

3xx (Redirection): The 3xx HTTP status code category indicates redirection. It means that the server is asking the client to take additional actions (such as following a new URL) in order to complete the request. These status codes are typically used when a resource has been moved or requires further steps to access.

Under on this category 3xx, there’s several way to access the new URL or address base on the status code response.

301: Moved Permanently (resource has permanently moved to a new URL).

Example

Imagine of having a current menu you have, using GET request/method,

http://appliances.com/washingmachine/10, you request and the response possible be 301 for instances which indicates that the URL use is outdated, or the information is already moved permanently. the header will be http://appliances.com/wetappliances/washingmachine/10

Response

{
  "message": "The requested inforation has already permanently moved in 
   new address.",
  "new_url": "http://appliances.com/wetappliances/washingmachine/10"
}

In this case, Postman will automatically follow the redirect and show the content from the new URL (http://appliances.com/wetappliances/washingmachine/10).

  • 302: Found (resource temporarily moved). In the case of a 302 Found, the resource has temporarily moved, and the client or customer should follow the new URL, but it might return to the original URL later. It maybe has a maintenance or migrate temporarily.

Example

Using GET method, you request http://rhedaliganstore.com/phone/30, The response will be 302 Found, and header is Location: http://bookstore.com/tempaddress-decembersale/phone/30.

The response body of request

{
  "message": "The resource has temporarily moved due to a christmas sale promotion.",
  "temporary_url": "http://bookstore.com/tempaddress-decembersale/phone/30"
}

In this case, the API tells the client to go to the temporary URL for the promotion, but the original URL might become active again later. So, it can go back once the offer, voucher, or sale already ended. So, the 302 is not permanently moved its just because possible to migrate for maintenance, or promotion and sale that necessarily need to move temporarily the information have.

  • 303: See Other (directs to another URL to complete the action).

After a POST request (for example, completing a book purchase), the server might redirect the client to a different URL to complete the process (such as a thank-you page).

Example

You request Using POST method, http://rhedsupermarket.com/checkout, and the body is

Body:
{
  "book_id": "22",
  "user_id": "16",
  "payment_method": "credit_card"
}

The response anticipate will be 303 see other,Headers:

Location: http://rhedsupermarket.com/thank-you, and the response body is:

  •   {
        "message": "Thank you for your purchase! You are being redirected to the confirmation page.",
        "redirect_url": "http://rhedsupermarket.com/thank-you"
      }
    

The API tells the client to visit a different URL (in this case, the thank-you page) to complete the action. In these examples, Postman will automatically follow the redirection and fetch data from the Location URL. This is how APIs communicate with clients, ensuring they reach the correct resource even if URLs change.

4xx (Client Error):

  • These errors occur when the request from the client (example coming from browser and Postman) is incorrect, unauthorized, or the resource can't be accessed.

    • 400 Bad Request: This indicates that the server could not understand the request due to malformed syntax or invalid parameters. The client should modify the request and try again. It often happens when the request lacks required fields or contains invalid data.

🍧Real life Analogy example🍧

  • Example, you're trying to order a book by filling out a form at a bookstore, but you forgot to write your name or book title. The bookstore tells you that the form is incomplete, and they can't process it.

Once we have feedback or response in API as 400 status code means the request was invalid or cannot be understood by the server.

Example Request Using GET METHOD

http://bookstore.com/order?book_id=

//should use a http://bookstore.com/order?book_id=123 so can specify what book ordered 
//so the response will be a bad request for the server since its missing.

The response will be status code of 400 and body

{
  "error": "Bad Request",
  "message": "The book_id is request input is invalid. Please provide a valid book_id."
}

In this case, the server is unable to process the request because required information is missing or malformed. In addition, the request is incomplete due to the typos, or incomplete format URL request.

  • 401 Unauthorized: This status code means the request has not been applied because it lacks valid authentication credentials. The server requires the client to authenticate (e.g., login), and the client must provide valid credentials to proceed.

🍧Real life Analogy example🍧

  • You try to enter a restricted section of the bookstore without showing your membership card. The bookstore tells you that you need to show your card to access that section.

Example using GET REQUEST

  • Once you receive response of 401 means authentication is required for the requested resource.

You request for instances

http://savemore.com/salehistory

The response is Status Code: 401 Unauthorized and body response is

{
  "error": "Unauthorized",
  "message": "Authentication is required to access your sale history."
}

In this code snippet, the server is telling you that you need to log in or provide authentication details to access this resource or the sale history.

  • 403 Forbidden: This code means the server understands the request but refuses to authorize it. The client might have valid credentials, but they do not have permission to access the resource. It can also occur if access is restricted for a certain group of users.

🍧Real life Analogy Example🍧

  • To make easier to understand, you have a savemore membership, but you try to access the "admin-only" section of the store. The savemore tells you that even though you're a member, you don't have permission to access that area.

Example using GET REQUEST

  • Once you received status code of 403 means the client or customer who requested does not have permission to access the resource.

Request URL

http://savemore.com/admin

The response Status Code: 403 Forbidden and the body response will be:

{
  "error": "Forbidden",
  "message": "You do not have permission to access the admin section of savemore."
}

In this scenario, even though you are authenticated as a member, the server refuses to give you access because your account doesn’t have the proper permissions. It depende on the condition and restriction for added features of the system. So very important of having a security measure and standard who are only allowed and not.

  • 404 Not Found: It indicates that the server cannot find the requested resource. The resource might have been removed, renamed, or the client might have entered an incorrect URL. It’s one of the most common HTTP errors when browsing websites.

🍧Real life Analogy Example🍧

  • For example, you’re looking for a book in the bookstore, but when you ask for it, the staff tells you that they don’t have that book in stock, or it doesn’t exist.

Example using GET REQUEST also

  • So, once you encountered this status code means the folder or components removed, renamed, or incomplete or typos URLs.

Request

http://bookstore.com/products/book/10000000

The response of the request will show the Status Code: 404 Not Found and the response body of the request will be

{
  "error": "Not Found",
  "message": "The requested book with ID 10000000 does not exist."
}

Mostly the 404 Not found is not about the latency of network but the configuration to access the file or folder due to the typing error, modifying, and the file range can’t be reach or found in the frame.

5xx (Server Error):

The 5xx HTTP status codes indicate server-side errors, meaning that the server failed to fulfill a valid request.

This is a generic error message when the server encounters an unexpected condition that prevents it from fulfilling the request.

500 Internal Server Error: This is a generic error message when the server encounters an unexpected condition that prevents it from fulfilling the request.

  • To give you a simple analogy, you're at a SM Fairview and eat dinner, and you place an order. Suddenly, the kitchen (as a SERVER) hits a problem maybe the stove breaks or the chef drops everything in the kitchen included of yours. They don’t know exactly what went wrong, but they can’t make your dish right now. They apologize, and not your problem, and they are responsible of that.

Request

api.serverdinner.com/newmenu/dinner

During request the response of server is Status Code: 500 Internal Server Error and the body response is

{
  "error": "Internal Server Error"
  "message": "Your order can't be process due to the debugging code system 
   and maintenance"
}

So, in this scenario, the server couldn't process the request due to an unexpected issue, such as a coding bug or misconfiguration.

503 Service Unavailable: This status code means the server is currently unable to handle the request, usually due to being temporarily overloaded or undergoing maintenance.

  • Simple analogy to understand this 503-http status code, that you're trying to buy a coffee from a coffee shop, but the barista tells you the coffee machine is temporarily down for maintenance, or there’s a long line of orders, so they can't serve you right now. However, they say they'll be able to help you once the issue is resolved, and you can try again later.

Example

  • Client requests a new bunch of coffee in coffee shop, but there’s a long in-line order. The server can’t be response and give a body context for the request

      {
        "error": "Service Unavailable"
         "message": "Please be patient, we can't service you right now because of 
      overload order on the line, we will help you once the issue is resolved. "
      }
      }
      //Possible of lack of resources or tools over their customer demands and needs.
    

So,, in this scenario, the API server can’t talk right now due to the possible conditions that may cause of unavailable services for the unexpected circumtances.

Key Differences:

  • 500 indicates a problem with the server itself that prevents the request from being processed.

  • 503 suggests that the server is temporarily unable to handle the request, but it may recover after some time.

Demonstrating in Postman:

  1. Open Postman and create a new request for each of these HTTP methods (GET, POST, DELETE).

  2. For each request, set the appropriate URL, method, and headers.

  3. Observe the response status codes (100 Informational, 200 OK, 201 Created, 204 No Content and so on ….) in the Postman Response tab.

These examples of HTTP status code I’ve created will help to demonstrate how the HTTP status codes correspond to typical operations in a RESTful API, helping clarify the behavior of the API in different scenarios used RESTFUL APIs.