Search code examples
c#asp.net-core.net-core

Consume API from API .NET CORE


I made some API with ASP.NET Core.
Then one of the API need to access 3rd party API. How can I do that?

Let say, the 3rd party API provide JSON format with 3 parameters (Name, address, phone) on it. The 3rd party API is to insert into table. My API will send a JSON format to the 3rd party API. How can I consume that from my API?

Below is one of my API code:
Controller:

[HttpPost]
    public async Task<IActionResult> InsertUpdate(Devloperr model)
    {
        try
        {
            var result = await repo.InsertUpdate(model);
            if (result > 0)
            {
                return Ok("Data has been saved");
            }
            return Ok("Data not saved");
        }
        catch (Exception e) { return StatusCode(500, e.Message); }
    }

Repository:

public async Task<int> InsertUpdate(Devloperr model)
        {
            mySqlConnection.Open();
            var cmd = mySqlConnection.CreateCommand();
            cmd.CommandText = @"SELECT `ID` FROM `Table1` WHERE `ID` =@ID";
            var data = await mySqlConnection.QueryAsync<Devloperr>(cmd.CommandText, param: new { ID = model.ID } );

            if (data.Count() == 1)
            {
               cmd.CommandText = @"UPDATE `Table1` SET `ID` = @ID, `NAMA` = @NAMA, `USERNAME` = @USERNAME WHERE `ID`=@ID ;";
                parameters.AddDynamicParams(model);
                var result = await mySqlConnection.ExecuteAsync(cmd.CommandText, parameters, commandType: sql);
                return result;
            }
            else
            {
                cmd.CommandText = @"INSERT INTO `Table1`(`ID`,`NAMA`,`USERNAME`) VALUES (@ID, @NAMA, @USERNAME);";
                parameters.AddDynamicParams(model);
                var result = await mySqlConnection.ExecuteAsync(cmd.CommandText, parameters, commandType: sql);
                return result;
               
            }

        }

Please advise.


Solution

  • My API will send a JSON format to the 3rd party API. How can I consume that from my API?

    You can register an IHttpClientFactory and use it to configure and create HttpClient instance in your ASP.NET Core Web API project, then make HTTP request(s) to that 3rd party API.

    Calling AddHttpClient to register IHttpClientFactory

    public void ConfigureServices(IServiceCollection services)
    {
        //...
    
        services.AddHttpClient();
    
        // ...
        // Remaining code deleted for brevity.
    }
    

    Make HTTP request from your API action

    var client = _clientFactory.CreateClient();
    //client.DefaultRequestHeaders.Add("Authorization", $"bearer {your_token_here}");
    
    var mdata = new { Name = "test", Address = "xxx", Phone = "123456789" };
    
    var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(mdata), System.Text.Encoding.UTF8, "application/json");
    
    
    var response = await client.PostAsync("https://xxxX/api/XXX", content);
    
    if (response.IsSuccessStatusCode)
    {
        //...
    }