0
0
Rest APIprogramming~5 mins

Why status codes communicate outcomes in Rest API

Choose your learning style9 modes available
Introduction

Status codes tell us if a request to a server worked or not. They give a quick answer without needing to read the full message.

When you want to know if a webpage loaded successfully.
When an app sends data to a server and needs to know if it was saved.
When checking if a login attempt was accepted or denied.
When a server needs to tell a client that something went wrong.
When you want to handle different results differently in your code.
Syntax
Rest API
HTTP/1.1 200 OK
HTTP/1.1 404 Not Found
HTTP/1.1 500 Internal Server Error

Status codes are 3-digit numbers sent by the server.

The first digit groups the type of response (e.g., 2xx means success, 4xx means client error).

Examples
This means the request was successful and the server is sending the requested data.
Rest API
HTTP/1.1 200 OK
This means the server could not find the requested page or resource.
Rest API
HTTP/1.1 404 Not Found
This means something went wrong on the server side.
Rest API
HTTP/1.1 500 Internal Server Error
Sample Program

This simple server sends a 200 status code with a message when you visit the root URL. For any other URL, it sends a 404 status code.

Rest API
from http.server import BaseHTTPRequestHandler, HTTPServer

class SimpleHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(b'Hello, world!')
        else:
            self.send_response(404)
            self.end_headers()

if __name__ == '__main__':
    server = HTTPServer(('localhost', 8000), SimpleHandler)
    print('Server running on http://localhost:8000')
    server.serve_forever()
OutputSuccess
Important Notes

Always check status codes to understand what happened with your request.

Different status codes help your app respond correctly to success or errors.

Summary

Status codes quickly tell if a server request worked or failed.

They use 3-digit numbers grouped by type (success, error, etc.).

Using status codes helps apps handle responses properly.