Example #1
0
        /// <summary>
        /// Async Method to consume the PetAPI
        /// returns a list of PetOwners with their registered pets
        /// </summary>
        /// <returns>List<PetOwners></PetOwners></returns>
        public async Task <StandardResponse <List <PetOwner> > > GetPetOwnersAsync()
        {
            var stdResponse = new StandardResponse <List <PetOwner> >();

            try
            {
                var baseUrl = _repoConfig.Url;
                _logger.LogDebug($"Path for the WebAPI is {baseUrl}");
                //Set the baseUrl here to allow for changes in the middle of execution
                _httpClient.BaseAddress = new Uri(baseUrl);
                _httpClient.DefaultRequestHeaders.Accept.Clear();
                _httpClient.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await _httpClient.GetAsync(baseUrl);

                _logger.LogDebug($"Http Response Code is {response.StatusCode}");

                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();

                    if (!result.IsNullOrEmpty())
                    {
                        //NOTE: Talk to business about considering caching of the results using Polly.Cache
                        var petOwnersList = JsonConvert.DeserializeObject <List <PetOwner> >(result);
                        _logger.LogDebug($"Http Request resulted with {petOwnersList.Count} owners");

                        stdResponse.Success = true;
                        stdResponse.Result  = petOwnersList;
                    }
                }
                else
                {
                    throw new Exception($"Error occured with response code - {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                stdResponse = StandardResponse <List <PetOwner> > .GenericError(ex.Message);
            }
            return(stdResponse);
        }