Call CRUD(GET, POST, PUT, DELETE) API using WebClient in c#
Here We will see how we can call all CRUD methods (GET, PUT, POST, DELETE) with the help of WebClient in c#.
you will need to add reference of "System.Web.Extensions" assembly to your project.
1. Call POST API :-
string apiUrl = "http://localhost:26404/api/POSTAPI";
object input = new
{
Name = txtName.Text.Trim()
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/PostCustomers","POST", inputJson);
2. Call GET API :-
string apiUrl = "http://localhost:26404/api/GETAPI";
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
string json = client.DownloadString(apiUrl + "/GetCustomers");
3. Call PUT API :-
string apiUrl = "http://localhost:26404/api/PUTAPI";
object input = new
{
Name = txtName.Text.Trim(),
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/PutCustomers/1", "PUT" , inputJson);
4. Call DELETE API :-
string apiUrl = "http://localhost:26404/api/DELETEAPI";
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
string json = client.UploadString(apiUrl + "/DeleteCustomers/1", "DELETE" , "");
Comments
Post a Comment