0
0
Rest APIprogramming~5 mins

429 Too Many Requests in Rest API

Choose your learning style9 modes available
Introduction

This status code tells you that you are sending too many requests to a server in a short time. It helps protect the server from being overloaded.

When a user tries to refresh a webpage many times quickly.
When an app sends too many data requests to a server in a loop.
When an API limits how many times you can ask for data in one minute.
When a website wants to stop spam or abuse from too many requests.
When a server wants to keep its service fast and fair for everyone.
Syntax
Rest API
HTTP/1.1 429 Too Many Requests
Retry-After: seconds_or_date

The status line shows 429 as the code and 'Too Many Requests' as the message.

The 'Retry-After' header tells the client when to try again.

Examples
The client should wait 120 seconds before sending another request.
Rest API
HTTP/1.1 429 Too Many Requests
Retry-After: 120
The client should wait until the given date and time before retrying.
Rest API
HTTP/1.1 429 Too Many Requests
Retry-After: Wed, 21 Oct 2024 07:28:00 GMT
Sample Program

This small server always replies with a 429 status and tells the client to wait 30 seconds before retrying.

Rest API
from http.server import BaseHTTPRequestHandler, HTTPServer

class SimpleHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Simulate too many requests error
        self.send_response(429)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Retry-After', '30')
        self.end_headers()
        self.wfile.write(b'Too Many Requests. Please wait 30 seconds.')

if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, SimpleHandler)
    print('Server running on port 8000...')
    httpd.serve_forever()
OutputSuccess
Important Notes

Always respect the 'Retry-After' header to avoid being blocked.

Servers use 429 to keep services stable and fair for all users.

Clients should handle 429 by waiting and retrying later.

Summary

429 means you sent too many requests too fast.

Servers tell you when to try again using 'Retry-After'.

Waiting before retrying helps keep services working well.