We'll use Postman to test a RESTful OData Web API application, sending an HTTP POST request. We'll start with a working OData Web API built on an ODataController , which we built in a previous tutorial, and we'll create an entry using Postman . After we create a new record , we check it sending an HTTP GET request :
In order to get Postman , just go to the Tools >> Extensions on Chrome , do a search for "Postman" and install the App .
HTTP POST Request to a RESTful ODataController Web API Service using Postman
Open Postman and select "POST" from the list :
Now let's learn how to call the OData Web API : in MVC , in order to setup the ODataController , there must be an ODataModelBuilder registered at the "Register" method called from the Global.asax file : as you see in the following snapshot , the EntitySet name MUST be the name of the Controller ( "Notes" in our case ) , so we'll look for a "NotesController" ODataController at the application :
Also , there is a route prefix declared ( "ODataV4" ) , so we'll append it to the URI .
Why are we checking this ? Because we want to know which kind of object is the ODataController method expecting : in our case , it expects a "Note" object , which must be included in the request's body ( "[FromBody]" ) . How to create a Note object ? Look at the declaration inside the Model :
Now we know that a Note must include all of those properties.
You could send an OData request asking for the METADATA information to construct the Note object , but that way you won't know the constraints declared with Data Annotations at the Model :
http://localhost:21435/ODataV4/$metadata
The Port of the application can be extracted from the Web tab at the application properties:
Put all of this together , and you have the URI for the POST request : "http://localhost:21435/ODataV4/Notes" :
Important : OData protocol is case sensitive : therefore , if you type "notes" instead of "Notes" , you will not reach the controller.
After setting the URI and the POST method , set the "Content-Type" header :
Next , build the JSON object to be sent inside the request's body , according to the Data Annotations :
Send the request :
Postman is waiting for the response :
In the meantime , the ODataController at the RESTful WebAPI have gotten the JSON object and bound it to a local variable :
The action method renders a response with code 201 CREATED , and Postman exposes it :
Finally , if you want to , send a HTTP GET request to check for the new record added to the database :
That's all...
In this tutorial we've learned how to send an HTTP POST Request to a RESTful ODataController Web API Service using Postman.Happy programming.....
By Carmel Shvartzman
כתב: כרמל שוורצמן
No comments:
Post a Comment