What is 405 Status Code: Meaning and Usage in REST APIs
405 status code means "Method Not Allowed". It tells the client that the HTTP method used (like GET or POST) is not supported by the server for the requested URL.How It Works
Imagine you are at a restaurant and you ask for a dish that the kitchen does not serve. The waiter politely tells you that the dish is not available. Similarly, when a client sends a request to a server using an HTTP method that the server does not allow for that URL, the server responds with a 405 Method Not Allowed status code.
This status code means the server understands the request and the URL exists, but the method (like POST, GET, PUT, DELETE) is not supported for that resource. The server usually includes an Allow header in the response listing the methods that are allowed.
Example
from http.server import BaseHTTPRequestHandler, HTTPServer class SimpleHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(b'Hello, GET method is allowed!') def do_POST(self): self.send_response(405) self.send_header('Allow', 'GET') self.end_headers() self.wfile.write(b'Method Not Allowed') if __name__ == "__main__": server_address = ('', 8000) httpd = HTTPServer(server_address, SimpleHandler) print('Server running on port 8000...') httpd.serve_forever()
When to Use
Use the 405 Method Not Allowed status code when your server receives a request with an HTTP method that is not supported for the requested resource. For example, if your API endpoint only supports GET requests to fetch data, but a client sends a POST request to create data, respond with 405.
This helps clients understand that the URL is valid but the method is wrong, so they can adjust their request accordingly. It also improves API clarity and prevents misuse.
Key Points
- 405 means the HTTP method is not allowed on the requested URL.
- The server usually sends an
Allowheader listing allowed methods. - It indicates the URL exists but the method is wrong.
- Helps clients fix their requests by knowing which methods are accepted.