title: Calling Rest API in a loop
body: <p>Let's assume I get game orders by calling a local web site's API. (A local web site selling game codes, when a user makes a purchase on the web site, I am getting orders from this web site's API.) I will do this with a .net core console app which will check the web site's API every 10 minutes. Now assume I get 5 game orders from the web site's API. Inside of this .net core console app, I will call my API in order to complete the purchase of these 5 game orders as follows. (I am calling 3rd party Rest APIs in order to get game codes.)</p>
  <p>Can you please check my code and give me some feedback\suggestions? Is there any place to cause a problem?</p>
  <pre><code>static async Task Main(string[] args)
          {
            // Assume I am getting game orders from the web site here
            //
              .....
  
              const int numberOfProducts = webSiteGameOrders;
              try
              {
                  for (var i = 0; i &lt; numberOfProducts; i++)
                  {
                      var product = webSiteProduct;
                     
                      //DEV
                      var request =
                          (HttpWebRequest)WebRequest.Create(&quot;http://test//api/purchase&quot;);
  
                      var svcCredentials =
                          Convert.ToBase64String(
                              Encoding.ASCII.GetBytes(&quot;username&quot; + &quot;:&quot; + &quot;password&quot;));
  
                      request.Headers.Add(&quot;Authorization&quot;, &quot;Basic &quot; + svcCredentials);
                      request.Method = &quot;POST&quot;;
                      request.KeepAlive = false;
                      request.ContentType = &quot;application/x-www-form-urlencoded&quot;;
  
                      var content = new FormUrlEncodedContent(new[]
                      {
                          new KeyValuePair&lt;string, string&gt;(&quot;productCode&quot;, webSiteProduct),
                          new KeyValuePair&lt;string, string&gt;(&quot;quantity&quot;, &quot;1&quot;),
                          new KeyValuePair&lt;string, string&gt;(&quot;shopNo&quot;, &quot;1&quot;),
                          new KeyValuePair&lt;string, string&gt;(&quot;safeNo&quot;, &quot;1&quot;),
                          new KeyValuePair&lt;string, string&gt;(&quot;cashierNo&quot;, &quot;1&quot;)
  
                      });
  
  
                      var formUrlEncodedContent = content;
                      var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();
  
                      using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
                      {
                          streamWriter.Write(urlEncodedString);
                      }
  
                      var httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
  
                      var response = new HttpResponseMessage
                      {
                          StatusCode = httpResponse.StatusCode,
                          Content = new StreamContent(httpResponse.GetResponseStream()),
                      };
  
                      //Read response
                      var htmlResponse = await response.Content.ReadAsStringAsync();
                      var deserializedResult = JObject.Parse(htmlResponse);
                      
                      Console.WriteLine((string)deserializedResult[&quot;coupons&quot;]?[0]?[&quot;Serial&quot;] + &quot;:&quot; + (string)deserializedResult[&quot;coupons&quot;]?[0]?[&quot;Pin&quot;]);
                  }
  
                
  
              }
              catch (Exception e)
              {
                  
                  Console.WriteLine(e.Message);
                  throw;
              }
          }
  </code></pre>
  <p><strong>UPDATE:</strong>
  Here is how I end up:</p>
  <pre><code>    public class BusinessService : IHostedService
      {
          private IHttpClientFactory _httpClientFactory;
          private readonly IHostApplicationLifetime _applicationLifetime;
          private IConfiguration _configuration;
          private readonly ILogger _logger;
          public BusinessService(IHttpClientFactory httpClientFactory, IHostApplicationLifetime applicationLifetime, IConfiguration configuration, ILogger&lt;BusinessService&gt; logger)
          {
              _httpClientFactory = httpClientFactory;
              _applicationLifetime = applicationLifetime;
              _configuration = configuration;
              _logger = logger;
          }
  
          public async Task StartAsync(CancellationToken cancellationToken)
          {
              _logger.LogCritical(&quot;Critical!&quot;);
              _logger.LogInformation(&quot;Application starts: &quot;);
              await MakeRequestsToRemoteService();
              //Stop Application
              _applicationLifetime.StopApplication();
              _logger.LogInformation(&quot;Application stops: &quot;);
          }
  
          public async Task MakeRequestsToRemoteService()
          {
              try
              {
                  HttpClient httpClient = _httpClientFactory.CreateClient(&quot;OrdersClient&quot;);
  
                  var authenticationBytes = Encoding.ASCII.GetBytes(&quot;zWedH5OUUp&quot;);
  
                  httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Basic&quot;,
                      Convert.ToBase64String(authenticationBytes));
                  httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));
  
                  var response = await httpClient.GetAsync(&quot;https://api.test.com/orders?startDate=1612126800000&quot;);
  
  
                  if (response.IsSuccessStatusCode)
                  {
                      Root orders = await response.Content.ReadAsAsync&lt;Root&gt;();
  
  
                      foreach (var content in orders.Content)
                      {
                          Console.Write(content.CustomerId + &quot; &quot; + content.CustomerFirstName + &quot; &quot; +
                                        content.CustomerLastName + &quot; &quot; + content.CustomerEmail + &quot; &quot; + content.TotalPrice +
                                        &quot; &quot; + content.InvoiceAddress.Phone + &quot; &quot; + content.Lines[0].ProductCode + &quot; &quot; +
                                        content.Lines[0].ProductName);
  
                          _logger.LogInformation(&quot;Order {ID} {CustomerId}, {Name} {LastName}, {Phone}, {ProductCode}, {ProductName}, {Price}, {OrderDate} &quot;, content.Id, content.CustomerId, content.CustomerFirstName, content.CustomerLastName, content.InvoiceAddress.Phone, content.Lines[0].ProductCode, content.Lines[0].ProductName, content.TotalPrice, DateTimeOffset.FromUnixTimeMilliseconds(content.OrderDate).DateTime);
  
                          InsertData(content);
                      }
  
  
                  }
              }
              catch (Exception e)
              {
                  _logger.LogError(&quot;Error: {Error} &quot;, e.Message);
                  throw;
              }
              
              
              
          }
  
          public void InsertData(Content content)
          {
             
              var connString = _configuration[&quot;ConnectionStrings:Development&quot;];
              using (var sqlConnection = new SqlConnection(connString))
              {
                  sqlConnection.Open();
  
                  using (SqlCommand command = new SqlCommand())
                  {
                      command.Connection = sqlConnection;
                      string sql = @&quot;insert into Orders (id, customerId, firstName, lastName, phone, productCode, productName, price, orderDate, status) values (@id, @customerId, @firstName, @lastName, @phone, @productCode, @productName, @price, @orderDate, @status)&quot;;
                      command.CommandText = sql;
                      
                      try
                      {
                          command.Parameters.Add(&quot;id&quot;, SqlDbType.BigInt).Value = content.Id;
                          command.Parameters.Add(&quot;customerId&quot;, SqlDbType.Int).Value = content.CustomerId;
                          command.Parameters.Add(&quot;firstName&quot;, SqlDbType.VarChar).Value = content.CustomerFirstName;
                          command.Parameters.Add(&quot;lastName&quot;, SqlDbType.VarChar).Value = content.CustomerLastName;
                          command.Parameters.Add(&quot;phone&quot;, SqlDbType.VarChar).Value = content.InvoiceAddress.Phone;
                          command.Parameters.Add(&quot;productCode&quot;, SqlDbType.Int).Value = content.Lines[0].ProductCode;
                          command.Parameters.Add(&quot;productName&quot;, SqlDbType.VarChar).Value = content.Lines[0].ProductName;
                          command.Parameters.Add(&quot;price&quot;, SqlDbType.Float).Value = content.TotalPrice;
                          command.Parameters.Add(&quot;orderDate&quot;, SqlDbType.BigInt).Value = content.OrderDate;
                          command.Parameters.Add(&quot;status&quot;, SqlDbType.TinyInt).Value = 1; //Retrieved
  
                          command.ExecuteNonQuery();
                      }
                      catch (SqlException exception)
                      {
                          if (exception.Number == 2627) // Cannot insert duplicate key row in object error
                          {
                              _logger.LogInformation(&quot;Duplicate: {ID} &quot;, content.Id);
                          }
                          else
                          {
                              _logger.LogError(&quot;Error: {Error} &quot;, exception.Message);
                              throw; // Throw exception if this exception is unexpected
                          }
                             
                      }
                  }
              }
          }
  
          public Task StopAsync(CancellationToken cancellationToken)
          {
              return Task.CompletedTask;
          }
      }
  }
  </code></pre>