Site icon Tutexchange

How to Update data using the PUT Method in ASP.NET CORE WEB API Using HttpClient from .Net Core Console Application

Advertisements

In this article, we will learn how to update data using the PUT method in simple steps.

Using the PUT method we can either update or create new data, but in this article, we will use it for Updating data.

In previous articles, we have checked how to create and get data in simple steps below are the article’s links.

How to Consume WEB API GET Method in .Net Core Console Application

How to Consume WEB API GET Method with a parameter named id in .Net Core Console Application

How to POST DATA to ASP.NET CORE WEB API Using HttpClient from .Net Core Console Application

Let’s Get Started.

PUT API which we are going to call

If you see PUT API it takes 2 parameters as input id and Model. The id parameter is passed from URI. The model is populated from the body of the request.

Let’s first call PUT API using Postman

URI: – https://localhost:44373/api/Music/12

We have URI we are going to use this below Json object to update data using the PUT method.

{
  "Name": "Srivalli",
  "Length": "6",
  "Yearreleased": 2022,
  "Writer": "Chandrabose",
  "Singer": "Sid Sriram",
  "Genre": "Singing",
  "Rating": 5
}

We have set the setting header Content-Type: – application/json in POSTMAN to send the request. In response, we are going to get the same json object means data is updated if we don’t get the request which we have sent means something went wrong.

we are going to update the Length of the song from 5.50 min to 6 min.

Creating Console Application

For Consuming APIs, we have created a .Net Core Application which Target Framework .Net 6.0 with the name Consoleconsumer.

Steps to Update data using the PUT method.

  1. HttpClient class instance for sending HTTP Requests.
  2. Setting Base Address “https://localhost:44373”
  3. Setting Accept Header “application/json”
  4. Adding a class with the name SongsModel which has properties and fields of request json.
  5. The same SongsModel object we are also going to use while deserializing response.
  6. Next, we are calling PutAsync Method and Passing Request Uri (“/api/Music/{12}”). If we have seen in POSTMAN request, we have sent id in URI same we are going to do there and also HttpContent as a parameter to it which will send a PUT request to the specified Uri in an asynchronous way.
  7. DeserializeObject (response we are going to receive will be Json format which we need to map to .Net Type)

Configuring PUT Method

In this method we are going to first create an instance of HTTPclient after that we are going to set Base Address “https://localhost:44373“.

After setting the base address next we are going to add a class with similar properties and fields of API with takes input.

public class SongsModel
{
    public int SongId { get; set; }
    public string Name { get; set; }
    public string Length { get; set; }
    public int Yearreleased { get; set; }
    public string Writer { get; set; }
    public string Singer { get; set; }
    public string Genre { get; set; }
    public int Rating { get; set; }
}

After adding the class next we are going to create an instance of a class and set some hardcode data to it for the demo.

Next after assigning data to the class, we are going to create an instance of string content and pass content, encoding type and content type.

HttpContent body = new StringContent(JsonConvert.SerializeObject(songsModel), Encoding.UTF8, "application/json");

In this instance of string content, we are going to pass to PutAsync() method as an input parameter and also, we are going to set request Request-URI as (“/api/Music/{Id}”) Id (songid) is a dynamic parameter.

var response = client.PutAsync(requesturi, body).Result;

As the PutAsync method gets called we are going to receive a response and, in this response, the first thing we are going to do is check the Status of it if it is a success then we are going to read the response and then Deserialize it.

The response that we are going to receive is that if we get updated data which we have sent that means data is updated in the database successfully.

we are going to update the Length of the song from 5.50 min to 6 min.

Code Snippet of PUT Request

static async Task PutJsonData()
 {
     using var client = new HttpClient();
     client.BaseAddress = new Uri("https://localhost:44373");

     var songsModel = new SongsModel()
     {
         SongId = 12,
         Name = "Srivalli",
         Rating = 5,
         Length = "6",
         Genre = $"Singing",
         Singer = $"Sid Sriram",
         Writer = $"Chandrabose",
         Yearreleased = DateTime.Now.Year
     };

     string requesturi = $"/api/Music/{12}";
     HttpContent body = new StringContent(JsonConvert.SerializeObject(songsModel), Encoding.UTF8, "application/json");
     var response = client.PutAsync(requesturi, body).Result;

     if (response.IsSuccessStatusCode)
     {
         var content = await response.Content.ReadAsStringAsync();
         if (!string.IsNullOrEmpty(content))
         {
             var objDeserializeObject = JsonConvert.DeserializeObject<SongsModel>(content);

             Console.WriteLine("Data Updated Successfully.");

             if (objDeserializeObject != null)
             {
                 Console.WriteLine(objDeserializeObject.Name);
             }
         }
     }

 }

Calling PutJsonData Method in Main() Method

static void Main(string[] args)
{
    PutJsonData().Wait();
}
 

Snapshots of runtime request and response

While sending a PUT request.

Below snapshot of PUT API which shows populated parameters

Below snapshot after the deserializing Json object

In this article, we have learned how to Update data using the PUT Method in ASP.NET CORE WEB API Using HttpClient from .Net Core Console Application.

Hope you have liked it.

Welcome my New Dotnet Shorts #DOTNETSHORTS Series Hope you like it small and simple and focused.

Exit mobile version