Home > Software engineering >  ASP.NET Core Web API - How to Consume 3rd party API Based on Condition
ASP.NET Core Web API - How to Consume 3rd party API Based on Condition

Time:12-05

I am given a third party API to consume In my ASP.NET Core-6 Web API.

API:

"https://api.thirdpartycompany.com:2233/api/BranchDetail"

In appsettings.json I have:

"Endpoints": {
  "branchUrl": "https://api.thirdpartycompany.com:2233/api/BranchDetail"
}

API:

{
    "Branches": [
        {
            "BranchName": "Accra",
            "BranchNumber": 1,
            "BranchType": "Human Resource Agency",
            "Country": "Ghana"
        },
        {
            "BranchName": "Kumasi",
            "BranchNumber": 2,
            "BranchType": "Production",
            "Country": "Ghana"
        },
        ...
}

The core is as shown below:

Entity:

public class Branch
{
    public int Id { get; set; }
    public string BranchName { get; set; }
    public string BranchType { get; set; }
    public int BranchNumber { get; set; }
}

DTO:

public class BranchCreateUpdateDto
{
    public string BranchName { get; set; }
    public string BranchType { get; set; }
    public int BranchNumber { get; set; }
}

public class BranchResponse
{
    public List<BranchCreateUpdateDto> Branches
    {
        get;
        set;
    }
}

BaseResponse:

public class BaseResponse
{
    public bool Success { get; set; } = true;
    public string Message { get; set; }
}

Service:

Interface:

Task<BaseResponse> CreateBranchAsync();

Implementation:

public class AdminBranchService : IAdminBranchService
{
    private readonly ApplicationDbContext _dbContext;
    private readonly IMapper _mapper;
    private readonly IUnitOfWork _unitOfWork;
    private readonly ILogger _logger;
    private readonly IConfiguration _config;
    private readonly HttpClient _myClient;
    public AdminBranchService(
        ApplicationDbContext dbContext,
        IUnitOfWork unitOfWork,
        ILogger logger,
        IMapper mapper,
        IConfiguration config,
        HttpClient myClient
        )
    {
        _dbContext = dbContext;
        _mapper = mapper;
        _unitOfWork = unitOfWork;
        _logger = logger;
        _config = config;
        _myClient = myClient;
    }
    public async Task<BaseResponse> CreateBranchAsync()
    {
        var branchResponse = new BaseResponse();
        var branches = new List<Branch>();
        try
        {
            string branchUrl = _config.GetSection("Endpoints").GetValue<string>("branchUrl");
            _myClient.DefaultRequestHeaders.Accept.Clear();
            _myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = _myClient.GetAsync(branchUrl).Result;

            var stringResult = response.Content.ReadAsStringAsync().Result;
            BranchResponse list = JsonConvert.DeserializeObject<BranchResponse>(stringResult);
            foreach (var singleBranch in list.Branches)
            {
                Branch res = new Branch();
                if (_dbContext.Branches.Any(x => x.BranchName == singleBranch.BranchName))
                {
                    res.BranchNumber = singleBranch.BranchNumber;
                    _unitOfWork.Branches.Update(res);
                }
                else
                {
                    //set all fields here
                    res.BranchName = singleBranch.BranchName;
                    res.BranchNumber = singleBranch.BranchNumber;
                    await _unitOfWork.Branches.InsertAsync(res);
                }
                await _unitOfWork.Save();
            }              
            _logger.Information("Branches Added Successfully");
        }
        catch (Exception ex)
        {
            _logger.Error("An Error occured "   ex.ToString());
        }
        return branchResponse;
    }
}

As stated earlier, I am consuming a third party API, but I don't want to get all the data.

From

BranchResponse list = JsonConvert.DeserializeObject<BranchResponse>(stringResult);

I want to get or deserialize only the data where BranchType Contains "Human Resource" or "Production"

How do I achieve this?

Thank you

CodePudding user response:

You can filter the list of branches using LINQ once they're deserialized, like so:

List<BranchCreateUpdateDto> branches;
var filtered = branches.Where(x => x.BranchType.StartsWith("Human Resource"));

The AdminBranchService might look like this (I also changed the async calls to be properly awaited):

public class AdminBranchService : IAdminBranchService
{
    private readonly ApplicationDbContext _dbContext;
    private readonly IMapper _mapper;
    private readonly IUnitOfWork _unitOfWork;
    private readonly ILogger _logger;
    private readonly IConfiguration _config;
    private readonly HttpClient _myClient;

    public AdminBranchService(
        ApplicationDbContext dbContext, 
        IUnitOfWork unitOfWork, 
        ILogger logger, 
        IMapper mapper, 
        IConfiguration config, 
        HttpClient myClient)
    {
        _dbContext = dbContext;
        _mapper = mapper;
        _unitOfWork = unitOfWork;
        _logger = logger;
        _config = config;
        _myClient = myClient;
    }

    public async Task<BaseResponse> CreateBranchAsync()
    {
        var branchResponse = new BaseResponse();
        var branches = new List<Branch>();

        try
        {
            string branchUrl = _config.GetSection("Endpoints").GetValue<string>("branchUrl");

            _myClient.DefaultRequestHeaders.Accept.Clear();
            _myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await _myClient.GetAsync(branchUrl);
            var stringResult = await response.Content.ReadAsStringAsync();
            BranchResponse list = JsonConvert.DeserializeObject<BranchResponse>(stringResult);

            // filter branches based on BranchType
            var filteredBranches = list.Branches
                .Where(x => x.BranchType.StartsWith("Human Resource")
                    || x.BranchType.StartsWith("Production"));

            foreach (var singleBranch in filteredBranches)
            {
                Branch res = new Branch();

                if (_dbContext.Branches.Any(x => x.BranchName == singleBranch.BranchName))
                {
                    res.BranchNumber = singleBranch.BranchNumber;
                    _unitOfWork.Branches.Update(res);
                }
                else
                {
                    //set all fields here
                    res.BranchName = singleBranch.BranchName;
                    res.BranchNumber = singleBranch.BranchNumber;
                    await _unitOfWork.Branches.InsertAsync(res);
                }
                await _unitOfWork.Save();
            }              

            _logger.Information("Branches Added Successfully");
        }
        catch (Exception ex)
        {
            _logger.Error("An Error occured "   ex.ToString());
        }

        return branchResponse;
    }
}

CodePudding user response:

May be you can add a middleware to check for the response and filter that out.

  • Related