kevbite / CompaniesHouse.NET

A simple .NET client wrapper for CompaniesHouse API
MIT License
37 stars 44 forks source link

The best way to handel the 429 (too many request) response ? #137

Closed orchardc closed 3 years ago

orchardc commented 3 years ago

@kevbite First of all, thanks so much for sharing this api, which is very useful and time-saving!

As CompaniesHouse set per application rates:

You can make up to 600 requests within a five-minute period. If you exceed this limit, you will receive a 429 Too Many Requests HTTP status code for each request made within the remainder of the five-minute window. At the end of the period, your rate limit will reset back to its maximum value of 600 requests. https://developer.company-information.service.gov.uk/api/docs/index/gettingStarted/rateLimiting.html

What is the best way to handel the 429 error when using this code? As the code shown doesn't have the response status (i.e. 429).


                        var request = new SearchRequest()
                        {
                            Query = "My company",
                            StartIndex = 0,
                            ItemsPerPage = 10
                        };

                        var result = await client.SearchCompanyAsync(request);
kevbite commented 3 years ago

Hello @orchardc, the method will throw a HttpRequestException exception with a message containing the unsuccessful status code. You could do something like the following:

try
{
    result = await client.SearchCompanyAsync(request);
}
catch (HttpRequestException ex) when (ex.Message.StartsWith("Response status code does not indicate success: 429"))
{
    // wait for a bit and then maybe retry.
}
orchardc commented 3 years ago

Got it, thanks Kevin!