Home > Software design >  Web API PUT,DELETE, POST methods via URI
Web API PUT,DELETE, POST methods via URI

Time:05-02

I am very new to the whole consept of API's. So far, I managed to build a web api that has GET,POST,PUT and DELETE methods.

Now, from an ASP.NET project, I try to finally use my web api.

Here's what I do for GET method:

string info = new WebClient() { }.DownloadString("https://mywebapisite.com/item/"   id);
Item item = JsonConvert.DeserializeObject<Item>(info);

This functions all fine. As you can see, all the GET method needs is an id.

However, for the POST method, I have no clue what to do. I can create a new Item instance, but don't know what to do with it.

By the way, I also used ASP.NET to make my web.api. There is a built-in feature in ASP.NET 5 called Swagger. It can perform all the tasks very succesfully. Is there like a code-behind for what Swagger does.

PS: I know that this question must be very common and basic. If you could refer me to another question in stackoverflow or simply tell me what to search on google I would appreciate it. (As you may guess, I don't even know what to search for)

CodePudding user response:

pseudo code to consume post request in C#

var requestObj = GetDummyDataTable();

using (var client = new HttpClient())  
{  
    // Setting Base address.  
    client.BaseAddress = new Uri("https://localhost:8080/");  
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
    HttpResponseMessage response = new HttpResponseMessage();  

   // HTTP POST  
   response = await client.PostAsJsonAsync("api/product", requestObj).ConfigureAwait(false);  
    
   if (response.IsSuccessStatusCode)  
   {  
      // Reading Response.  
      string result = response.Content.ReadAsStringAsync().Result;  
      var responseObj = JsonConvert.DeserializeObject<DataTable>(result);  
   }  
}  

CodePudding user response:

You can refer the following code to call the API using HttpClient:

////using System.Net.Http.Headers;
////using System.Text;
using (var client = new HttpClient())
{
    var requesturi = "https://localhost:7110/api/ToDo/relativeAddress";

    var item = new TestUserViewModel()
    {
        Name = "John Doe",
        Age = 33
    };
    ////using System.Text.Json;  // use JsonSerializer.Serialize method to convert the object to Json string. 
    StringContent content = new StringContent(JsonSerializer.Serialize(item), Encoding.UTF8, "application/json");

    //HTTP POST
    var postTask = client.PostAsync(requesturi, content);
    postTask.Wait();

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

        return RedirectToAction("Privacy");
    }
}

The API method like this:

[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{ 
    [HttpPost]
    [Route("relativeAddress")]
    public string GetAddress([FromBody] TestUserViewModel testUser)
    {
        return "Address A";
    }

And the result like this:

enter image description here

You can also refer this link to set the Content-Type.

  • Related