Use Web API in C#


Use Web API in C#


This tutorial is only for those Users, who are working with Web API  in C#.In past, some peoples ask me to help on How we will deal with Web API in C#,So Now let’s start our tutorial on Web API….

Introduction


Before we start our tutorial, we have to install Visual Studio because Visual Studio IDE is best for work on Web API,With  this IDE our project is going to be marvellous.

WE have to use the CustomFormatterclass which have to playing a important role in our project. In ASP.NET Web API MediaTypeFormatter, Now we have  to use this MediaTypeFormatter class in our project.

First,create a EmployeesController, which is exactly work like a Table and our details are saved there.

Now, We will have to ADD a POST Method inEmployeesController. This  POST method allows us to add a new details in our Data Table.

We have to create our Own Data Table with some rows and columns in our POST Method called post. Now, let’s go to our Visual Studio and we are going to implement our POST Method.

Now, In the POST Method we use attributes and we have added Data and instance as data, This is the place where our data is going from here and other methods use this...If a client want data, He has to request us and we have a request data header.The data here for the data object is going to come from request body and we tell that web API by declaring this Data in parameter with an attribute. We will specify an attribute, from Body attribute,which basically means this attribute will be telling the data for that data which we had specified in the parameter so our code with attribute is look like this :-

public void post_api(Datadata)
{

}

Now we have to create an instance of TestEntities DB Values :-

public void post _api(Data  data)
{
using (TESTEntities values = new TESTEntities())
{
values.empData.Add(data);
values.SaveChanges();
}


}

Now, let's save our changes and reload the project in Visual Studio. Now again go to your project and open it and apply the POST request.

To check on the browser we have to implement our URL in it we have use Https in it for the POST. Remember the POST method in previous above and we are going to use here that thing here-- that request is going to come from request body by declaring it from Body attribute so within the request body in the POST Method,  we have to include the data for the data object.

For this we have used some code’s here and uses request body as you guys see above in the program. So this is JSON formatted data so we need to tell Web API we will be sending JSON formatted data to tell that we include content-type header as,
Now, execute that request. When you will execute that request go to SQL and check whether data has been inserted or not.




We got 204 No content; that’s because the return type of the POST method is Void. By default Web API is going to return Status Code 204 No content.

According to the standards of REST when we add a new item we should be actually returning status code 201 item created and along with status code 204. We should also be returning the location which is the URI of the newly created item. So let’s use this in our program in example :-

Instead of Void we will write HttpResponseMessage,

As you can see from the above code we had used HttpResponseMessage instead of void and we had taken a variable which is message and in that whatever response is coming attached to a property called as created response and in that we are passing those HTTP status codes in that parameter.

Now we want to include status 201 which is the location of the newly created URI  -- to do that we will use message object,

public HttpResponseMessage post_api1 (Data data)
{
try
{
using (TESTEntities values = new TESTEntities())
{
values.empData.Add(data);
values.SaveChanges();

var message = Request.CreateResponse(HttpStatusCode.Created, data);
message.Headers.Location = new Uri(Request.RequestUri + data.ID.ToString());
return message;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest,ex);
}


}

We had created message Header and location property and in that we will be concating that URI to which the respective ID been created. We had included try catch, in catch we will be monitoring for Bad requests which are coming from HTTP. Now save the changes and reload the app and let’s issue a request in method in our program in C# in Visual Studio.

I had created another JSON data to execute this,

Now to SQL and see data,

As you can see from the data we had successfully inserted our data. Notice here the id is seven for a newly-created employee. Now let’s go to fiddler and let’s inspect the response we had got --  we will see,

Notice with the response code, the status code is 201 created and you can see the location as well URI of the newly created item as well. So copy that header value as

Paste the header value in the URL click on the URL

When you hit enter we got the newly created URI entities as expected. Now we will modify the GET method as well. First we write code for an employee whose id doesn’t exist in the database.

So in the fiddler we will specify an id that does not exist as,

So let’s execute this request

As you can see, we got the JSON which is NULL because we don’t have the id of that data which is requested.

Now, this is misleading, according to the standard of REST when an item is not found we should be actually returning status code 404 which stands for Not Found. Now let’s go to our Visual Studio and we have to create  a method in the program in C# and we will modify the implementation of GET method .

public HttpResponseMessage Get(int id)
{
using (TESTEntities values = new TESTEntities())
{
var data= values.empData.FirstOrDefault(e => e.ID == id);

if (data != null)
{
return Request.CreateResponse(HttpStatusCode.OK, data);
}

else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,"Rows With id = " + id.ToString() + " not found");
}

}
}

So, here we have modified our GET method here we had used a condition if entity is not null it will return a status code null;  then, it will return not found. Now, let’s run the project in Visual Studio,

Notice, now we have got 404 Not Found,

And look at the message we have got the employee with that ID is not found.

Now, if we request with a data id that does exist we will see.

Now, here we see the status code 200 OK and the data we had requested. 






Points to remember :-

  • ·      If a method type is void, by default status code is 204. No content is returned.
  • ·      When a new item is created, we should be returning status code 201 Item created.
  • ·      With 201 status code we should also include the location, URI of the newly created item.
  • ·      When an item is not found, instead of returning NULL and status code 200 OK, return 404 not Found status code along with a meaningful message such as Employee ID doesn’t exist.
                   Other Links 

>>> Python Basics                                 >>> Data Structure in Python

>>> CRUD/CURD in Django                   >>> Job Opportunities in Python


>>> Currency Detection By Image in Python     

                                       
>>> Access Network Drive with password in Python                              

>>> Pandas Tutorials

Reactions

Post a Comment

0 Comments