Showing posts with label HTTP-GET. Show all posts
Showing posts with label HTTP-GET. Show all posts

Saturday, July 11, 2020

Querying Entities' Properties in Web API OData RESTful with ODataController

In this article we enable the Querying of an Entity's Property in an Web API OData RESTful service with ODataController.
Our task here is to perform OData protocol queries in order to get the value of some Entity's property, the following query for example :
http://localhost:6954/Odata/Notes(10)/Body/$value


When developing an ODataController to create an OData Web API, having configurated the application properly, as in the previous tutorial, you get automatically support for the most common OData protocol's queries. You can then query the OData Web API using $metadata, $value, $select, $top, $skip, $filter and even $expand , to get the JSON response:
http://localhost:6954/OData/$metadata#Notes :

              /Odata/Notes?$filter=From eq 'Fry'





http://localhost:6954/OData/Notes?$skip=2&$top=10

http://localhost:6954/OData/Notes?$select=Body

There are some conventions to follow when developing an ODataController:

1) the controller's name must be the entity name, the root of the resource path:

      /Notes(10)      implies that the Web API will look for a controller named NotesController (case sensitive)

2) the Action name for fetching an Entity's property will be set according to the Entity type and the Property name, as follows:

  /Notes(10)/Body       
      means that the Web API will look for an Action method named GetBodyFromNote()

All this conventions can be found in the Microsoft Asp.Net official site.
Let's say we have an Entity named "Note" with some property called "Body" : we want to call the OData HTTP service with this URI:
      http://localhost:6954/Odata/Notes(10)/Body/

So, according to the OData protocol specification, we need an Action method named GetBodyFromNote(), marked with the attribute "[EnableQuery]" , which returns the required property from the Entity:


(COPY-PASTE THIS CODE) : 


 [EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
        public string GetBodyFromNote([FromODataUri]int key)
        {
            IEnumerable<Note> data = Repository.GetAll();
            var note = data.Where(n => n.ID == key) .SingleOrDefault();
            return note.Body ;
        }



Build & run the application, and type the URI to fetch the required property in JSON format:

http://localhost:6954/Odata/Notes(10)/Body/
Also, we can request ONLY the $value of the property:

http://localhost:6954/Odata/Notes(10)/Body/$value
That's all
In this post we've seen how we perform Querying Entities' Properties in Web API OData RESTful with ODataController. 

Enjoy programming.....
    By Carmel Shvartzman
כתב: כרמל שוורצמן

Tuesday, June 19, 2018

Make a WCF RESTful Web Service with CRUD operations in 5 minutes

In this Step by step we Make a WCF RESTful Web Service with CRUD operations in 5 minutes 
   we see how to build a WCF REST web service with all CRUD operations to be Ajax called, all this   in just 5 minutes, following this simple steps :

1) Use Visual Studio templates and build an Ajax WCF web service
2) Customize it to support RESTful calls in JSON format (can also be XML)
3) Code all C.R.U.D. (Create Read Update Delete) operations


The whole code for this tutorial , can be downloaded from the following GitHub repository:
https://github.com/CarmelSoftware/WCF_RESTful_WebService
To build this service, we use a demo class which will be exposed by the REST service through HTTP calls, that you can later replace with your own EDM data model classes.
This an HTTP GET response from this RESTful WCF service :

Make a WCF RESTful Web Service with CRUD operations in 5 minutes
And this other is an HTTP PATCH request-response from this WCF REST service:

Make a WCF RESTful Web Service with CRUD operations in 5 minutes



Make a WCF RESTful Web Service with CRUD operations in 5 minutes


The whole process for making this REST service , is as follows :

1) Use Visual Studio templates and build an Ajax WCF web service:

First build an ASP.NET Web Application using this Visual Studio template:


Make a WCF RESTful Web Service with CRUD operations in 5 minutes



Then, add an AJAX enabled WCF web service to the project:


Make a WCF RESTful Web Service with CRUD operations in 5 minutes

You'll get the following usable skeleton for the WCF service:


Make a WCF RESTful Web Service with CRUD operations in 5 minutes


Take a look at the web.config file to see the WCF service configuration:

Make a WCF RESTful Web Service with CRUD operations in 5 minutes


As you can see , there is an endpoint which wears the name of the Web service class.
The "enableWebScript " behavior sets that the service will respond to AJAX calls.


2) Customize it to support RESTful calls in JSON format (can also be XML)

First thing we do, is to change the endpoint behavior to turn it into a REST service, using the "webHttp" directive, as follows:

Make a WCF RESTful Web Service with CRUD operations in 5 minutes

Notice that this directive replaces the "enableWebScript" one.

To make run this service, we design a demo class called "Data", which will be exposed by the REST service through HTTP calls:

Make a WCF RESTful Web Service with CRUD operations in 5 minutes

This data will be decorated with the DataContract directive, and the properties will be DataMembers.
We also add some constructors to create some records and return them by the service.
After you have your WCF RESTful service working, you will replace this demo class with some EDM data model classes of your own.
Remember to declare "serializable" your model.



3) Code all C.R.U.D. (Create Read Update Delete) operations

Then go to the WCF class and replace the "DoWork" method with the HTTP GET method to return ALL  items:


HTTP GET :

Make a WCF RESTful Web Service with CRUD operations in 5 minutes

We specify the handle for HTTP GET requests, by using the attribute "WebGet".
Also, we stipulate the response format as JSON, since the default is XML.
And we set an UriTemplate as "/Get" , which will differentiate this method from the second GET one, which will return only one item according to the ID, which you will code as follows:

Make a WCF RESTful Web Service with CRUD operations in 5 minutes
Notice that the return value is an array of Data objects and a single Data object, accordingly:


Make a WCF RESTful Web Service with CRUD operations in 5 minutes

Make a WCF RESTful Web Service with CRUD operations in 5 minutes


HTTP POST :

The POST HTTP verb is used to CREATE a new item, and we define it using the WebInvoke attribute:

Make a WCF RESTful Web Service with CRUD operations in 5 minutes

We only want to check that our REST service works, so that just return the same Data object from the request (here i'm using POSTMAN to send HTTP requests. You can also use FIDDLER for that):


Make a WCF RESTful Web Service with CRUD operations in 5 minutes

Important: the JSON object in the request's body must hold the field's data with exactly the same field names set in the DataMembers in your service: it is case-sensitive ("Id" means "Id", and no "id", got it?).

HTTP PUT:

The PUT HTTP VERB is used to update the entire item, i.e. to replace it with an updated one, and we do so by using the WebInvoke PUT option as follows:


Make a WCF RESTful Web Service with CRUD operations in 5 minutes
The binder will give you the Date object from the request, if the names of the fields being the same as the class in a case-sensitive way, and also will give you the ID of the item to update. Check that you wrote EXACTLY the same variable name for this : "Put/{id}" == string "id" .

Test this method from POSTMAN sending an PUT request with a JSON object in the body:


Make a WCF RESTful Web Service with CRUD operations in 5 minutes

Important: the JSON object inside the request's body must contain the field's data with exactly the same field names set in the DataMembers in your service: it is case-sensitive ("Id" means "Id", and no "id").


HTTP PATCH :

The HTTP PATCH verb is used in REST for updating just some of the object's fields:


Make a WCF RESTful Web Service with CRUD operations in 5 minutes


Again, test it using this REST call with the HTTP PATCH verb:

Make a WCF RESTful Web Service with CRUD operations in 5 minutes
HTTP DELETE :


Finally, create the method to handle HTTP DELETE requests, as follows:




Make a WCF RESTful Web Service with CRUD operations in 5 minutes




Make a WCF RESTful Web Service with CRUD operations in 5 minutes


THE END


That's all. Now you have a working WCF RESTful web service , and you can replace the Data model with your own.


      by Carmel Schvartzman


כתב: כרמל שוורצמן


Tuesday, January 5, 2016

How to send an HTTP DELETE Request to a RESTful ODataController Web API Service using Postman

In this post we'll learn Step by step how to send an HTTP DELETE Request to a RESTful ODataController Web API Service using Postman. 
We'll use Postman to test a RESTful OData Web API application, sending an HTTP DELETE request. We'll use a working OData Web API ODataController  built in a previous tutorial,   and we'll delete a record using  Postman :

How to send an HTTP DELETE Request to a RESTful ODataController Web API Service using Postman




In order to get Postman installed ,  go to the Chrome Tools >> Extensions   ,  search for "Postman" and install the App .

HTTP DELETE Request to a RESTful ODataController Web API with Postman



Now let's see how to call the OData Web API to delete an item :   in order to setup  the ODataController , there will be an ODataModelBuilder at the "Register" method called from the Global.asax file : it's important that the EntitySet name MUST be the same name of the Controller   , therefore we'll look for a "NotesController"  at the application :

Because there is a route prefix set ( "ODataV4" ) ,  we'll also append it to the URL : 



At the ODataController ,  we check for the "Delete" action method , since we're sending an HTTP DELETE request :


Why are we checking this ? Because we want to know what is ODataController method expecting : in our case , it expects a URI which must include an integer "key" ID  ( "[FromODataURI]" ) .  

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 DELETE request : 

"http://localhost:21435/ODataV4/Notes(6)" :


Important : OData is case sensitive : therefore , if you type "notes" instead of "Notes" , you will not obtain any data.

After setting the URI and the DELETE method , write the "Content-Type" header :




Send the request :


The request details can be seen this way :


In the meantime , the ODataController at the RESTful WebAPI have handled the request with the ID in the ODataURI : 


The action method renders a response with code 410 "GONE" , to express that the record has been deleted , and Postman exposes it : 






That's all... 
In this tutorial we've learned how to send an HTTP DELETE Request to a RESTful  ODataController Web API Service using Postman.
Happy programming.....
      By Carmel Shvartzman
כתב: כרמל שוורצמן






Thursday, June 4, 2015

jQueryMobile using Ajax to load Json data to a Table

Here we review Step by step jQueryMobile using  Ajax  to load Json data to a Table For Android and BlackBerry
In this article we create in 20 minutes a jQuery Mobile App to load Json data to a toggle Table , where you can hide or display its columns,  via Ajax calls . This App is for use on all kind of Mobile devices : Nexus , iPad, iPhone, BlackBerry, Nokia,  Acer ,  ...
The data will be loaded in Json format via Ajax, in order to be displayed on this table .
This jQuery Mobile App looks like this:
jQueryMobile using  Ajax  to load Json data to a Table

jQueryMobile using  Ajax  to load Json data to a Table   1




jQueryMobile using  Ajax  to load Json data to a Table For Android and BlackBerry



For this article on jQuery Mobile , we'll be using the  jQuery and jQueryMobile Frameworks, so  browse to http://jquerymobile.com/ and jQuery , and obtain the latest versions of the frameworks via CDN  . If you want to use a Mobile Emulator, please refer to the following short tutorial on the Ripple Emulator.

After you got the files , add them to the Head of the HTML5 file:
jQueryMobile using  Ajax  to load Json data to a Table    2



First, add a Header with a NavBar , by making use of the data-role="page" and the data-role="header" , adding also a "fixed" attribute to fix the header in its place when the user scrolls the screen :
jQueryMobile using  Ajax  to load Json data to a Table    3


Create a "main" div element containing our table.  Use the data-role=table and the data-mode=columntoggle directives, which allow to display/hide the columns. However , if you don't write "columntoggle", the table will be shown in "Reflow" mode, then ALL columns will be displayed, and all the data will be grouped in chunks per row.
Inside the table,  define to each field a data-priority directive from 1 (most priority field) to 6 (less important column).
Notice that if you do not set a data-priority for a field, it will always be displayed:

jQueryMobile using  Ajax  to load Json data to a Table   4






We also write a button to call the function that brings the table data.

Finally, we code the markup for making a Footer with a Navbar :
jQueryMobile using  Ajax  to load Json data to a Table    5



The javascript which brings the data includes using the jQuery  $.ajax function, sending requests to the URL where is stored a file containing JSON data .
This HTTP GET request  tells the server that the data is expected in JSON format, so that the request's "Accept" header will include "application / json".

In case of successful performance, we do an $.each() loop on the received JSON data in the response, which includes key/value pairs, where the Key is the "id"  , and the Value is the Customer  JSON object.
Then, for each customer, we add to the tbody of the Table a Row with a Cell per column:

jQueryMobile using  Ajax  to load Json data to a Table    6


Is imperative that you REFRESH the Table after adding the Rows, therefore the table's Toggle functionality will work on the new rows.

We added also some style to this Mobile using the following  CSS3 file:
jQueryMobile using  Ajax  to load Json data to a Table  7


All the code can be downloaded from the following GitHub repository:


This is how the jQuery Mobile Toggle Table looks :
jQueryMobile using  Ajax  to load Json data

Json
load Json

to load Json

  Ajax  to load Json

using  Ajax  to load Json



We hope that this article was helpful for you...
Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן