0
0
Rest APIprogramming~5 mins

404 Not Found in Rest API

Choose your learning style9 modes available
Introduction

The 404 Not Found status tells you that the web address you asked for does not exist on the server.

When a user tries to visit a webpage that has been deleted or moved.
When an API client requests a resource that is not available.
When a user types a wrong URL in the browser.
When a link on a website points to a page that no longer exists.
When a server cannot find the requested file or data.
Syntax
Rest API
HTTP/1.1 404 Not Found
Content-Type: text/html

<html>
  <head><title>404 Not Found</title></head>
  <body>
    <h1>Not Found</h1>
    <p>The requested URL was not found on this server.</p>
  </body>
</html>

The first line is the status line with code 404 and reason phrase 'Not Found'.

The body usually contains a message to explain the error to the user.

Examples
This example shows a JSON response for an API returning 404.
Rest API
HTTP/1.1 404 Not Found
Content-Type: application/json

{"error": "Resource not found"}
A simple HTML page telling the user the page was not found.
Rest API
HTTP/1.1 404 Not Found
Content-Type: text/html

<html><body><h1>404 Not Found</h1></body></html>
Sample Program

This Python program creates a simple web server. It responds with 'Hello, world!' when you visit /hello. For any other URL, it sends a 404 Not Found response with a message.

Rest API
from http.server import BaseHTTPRequestHandler, HTTPServer

class SimpleHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/hello':
            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.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(b'404 Not Found: The requested resource was not found.')

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

404 is a client error status code, meaning the client asked for something that does not exist.

Always provide a helpful message or page so users know what happened.

Custom 404 pages improve user experience by guiding users back to working parts of the site.

Summary

404 Not Found means the server cannot find the requested resource.

It is used when a URL or API endpoint does not exist.

Servers should send a clear message to help users understand the error.