I'm attempting to query the public NPPES NPI registry using Flurl as my HTTP client library, version 2.4.2.
After 4-5 successful async requests (debugging by stepping through each request in the loop) it always fails with a SocketException that the connection was forcibly closed. I'm assuming the API is rate limited, but slowing down the requests doesn't seem to be working. Here is my relevant code.
static async Task<Result> GetNpiEntry(string npiNumber)
{
var npiEntry = await "https://npiregistry.cms.hhs.gov"
.AppendPathSegment("api/")
.SetQueryParams(new { version = "2.1", number = npiNumber }).GetJsonAsync<RootObject>();
return npiEntry.results[0];
}
and the loop calling it with a hefty sleep between requests.
List<Result> npiResults = new List<Result>(npiTable.Rows.Count);
foreach (DataRow row in npiTable.Rows)
{
Result npiEntry = Task.Run(() => GetNpiEntry((string)row[0])).Result;
npiResults.Add(npiEntry);
Thread.Sleep(2000);
}
Here's the actual exception.
---> System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
---> System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host.
Is there some more appropriate way for me to debug or do this? I imagine I'd need to rate limit the client, but shouldn't a generous wait time between requests work at least for debugging?