Home > Software engineering >  ASP.NET Core Web API - How to pass specified fields as payload to third party API
ASP.NET Core Web API - How to pass specified fields as payload to third party API

Time:06-18

I have this third party api in ASP.NET Core-6 Web API

http://api.thirdpartycompany.com:2233/api/EmployeeDetail

So, I did this:

appsettings.json:

  "Endpoints": {
    "EmployeeUrl": "http://api.thirdpartycompany.com:2233/api/EmployeeDetail"
  }

DTO:

public class EmployeeDataRequest
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string EmployeeCode { get; set; }

    public decimal Salary { get; set; }

    public string Location { get; set; }

    public string Email { get; set; }
}

Service:

public class EmployeeService : IEmployeeService
{
    private readonly HttpClient _httpClient;
    private readonly HttpHelper _httpHelper;
    private readonly IConfiguration _config;
    private readonly IUnitOfWork _unitOfWork;
    private readonly string baseUrl;

    public EmployeeService(
        HttpClient httpClient,
        HttpHelper httpHelper,
        IUnitOfWork _unitofwork,
        )
    {
        _httpClient = httpClient;
        _httpHelper = httpHelper;
        _config = config;
        _unitOfWork = _unitofwork;
        baseUrl = config.GetSection("Endpoints").GetValue<string>("baseUrl");
    }

    public async Task<BaseResponse> EmployeeDetail(EmployeeDataRequest payload)
    {
        var response = new BaseResponse();
        using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            try
            {
                var employee = new Employee
                {
                    FirstName = payload.FirstName,
                    LastName = payload.LastName,
                    EmployeeCode = payload.EmployeeCode,
                    Salary = payload.Salary
                    Location = payload.Location,
                    Salary = payload.Salary,
                    Email = payload.Email
                };
                await _unitOfWork.Employees.InsertAsync(employee);
                await _unitOfWork.Save();

                var headers = new Dictionary<string, string>();
                headers.Add("Authorization", $"Bearer {token.access_token}");

                var employeeEndPoint = baseUrl   _config.GetSection("Endpoints").GetValue<string>("EmployeeUrl");
                var httpResponse = _httpHelper.PostOrPutRequest(uri: employeeEndPoint, methodType: HttpMethod.Post, model: payload, headers: headers).Result;
                if (httpResponse != null)
                {
                    if (httpResponse.StatusCode == HttpStatusCode.OK)
                    {
                        response = JsonConvert.DeserializeObject<EmployeeDataResponse>(content);
                    }
                    else
                    {
                        response = new BaseResponse { ResponseCode = httpResponse.StatusCode.ToString(), ResponseDescription = httpResponse.ReasonPhrase };
                    }
                }
                transaction.Complete();
            }
            catch (Exception ex)
            {
                response = new BaseResponse { response_code = "96", response_description = "Error occured, contact admin" };
            }
            return response;
        }
    }
}

I want to insert the data into the Database (Employee Table), and then pass some of the fields as payload to the third party API (EmployeeUrl).

From EmployeeDetail Service above, I successfully inserted all the fields into Employee table and passed all the fields in EmployeeDataRequest as payload into the third party api as done in httpResponse as payload

However, I want to exclude these fields (Salary and Location) from going into the third party api (I only want to insert them into the Employee table). But pass the other fields (FirstName, LastName, EmployeeCode and Email).

How do I achieve this?

Thank you.

CodePudding user response:

If EmployeeDataRequest can be assumed to be a DTO used within your application as an internal service call when your EmployeeService's methods are called, then you should not pass it to the external party.

Instead, map from EmployeeDataRequest DTO to ThirdPartyEmployeeDetail DTO. This is to decouple the usage of each DTO.

So if in the future, EmployeeDataRequest DTO needs a new EmployeePosition property, it will not affect your 3rd party API call at all.

Create a class:

public class ThirdPartyEmployeeDetail
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string EmployeeCode { get; set; }

    public string Email { get; set; }
}

Then, map and call your 3rd party API.

var apiPayLoad = new ThirdPartyEmployeeDetail()
{
    FirstName = payload.FirstName,
    LastName = payload.LastName,
    EmployeeCode = payload.EmployeeCode,
    Email = payload.Email
};

var httpResponse = _httpHelper.PostOrPutRequest(uri: employeeEndPoint, methodType: HttpMethod.Post, model: apiPayLoad , headers: headers).Result;

The mapping itself, if it is going to be repeated on your other API calls to the 3rd party sercice, you may extract the logic into another class to convert and return ThirdPartyEmployeeDetail when EmployeeDataRequest is passed as a parameter.

CodePudding user response:

you create an interface that contains the properties associated to 3rd party

  public interface IEmployeeDataRequestForThirdParty
    {
        string FirstName { get; set; }

        string LastName { get; set; }

        string EmployeeCode { get; set; }

        string Email { get; set; }
    }

 public class EmployeeDataRequest : IEmployeeDataRequestForThirdParty
    {
        public string FirstName { get; set; };

        public string LastName { get; set; };

        public string EmployeeCode { get; set; };

        public decimal Salary { get; set; };

        public string Location { get; set; };

        public string Email { get; set; };
    }

before sending it to your post you can cast

_httpHelper.PostOrPutRequest(uri: employeeEndPoint, methodType: HttpMethod.Post, model: (IEmployeeDataRequestForThirdParty) payload, headers: headers).Result;

so the object would be serialized with only exposed properties from the interface.

I have not tested this, but this approach should work, the other option would be you could create a base class of 3rd party then you can inherit from EmployeeDataRequest

  • Related