Pages

WEB API RESTful API

Web APIs has become an very important topic in the last year. We at M-Way Solutions are working every day with different backend systems and therefore we know about the importance of a clean API design.

Typically we use a RESTful design for our web APIs. The concept of REST is to separate the API structure into logical resources. There are used the HTTP methods GET, DELETE, POST and PUT to operate with the resources.

Good practices to design a clean RESTful API:

Use nouns but no verbs

For an easy understanding use this structure for every resource:

Resource GET read POST create PUT update DELETE
/cars Returns a list of cars Create a new ticket Bulk update of cars Delete all cars
/cars/711 Returns a specific car Method not allowed (405) Updates a specific ticket Deletes a specific ticket

Do not use verbs:

/getAllCars
/createNewCar
/deleteAllRedCars

GET method and query parameters should not alter the state

Use PUT, POST and DELETE methods instead of the GET method to alter the state.

Do not use GET for state changes:

GET /users/711?activate or
GET /users/711/activate

Use plural nouns

Do not mix up singular and plural nouns. Keep it simple and use only plural nouns for all resources.

/cars instead of /car
/users instead of /user
/products instead of /product
/settings instead of /setting

Use sub-resources for relations

If a resource is related to another resource use subresources.

GET /cars/711/drivers/ Returns a list of drivers for car 711
GET /cars/711/drivers/4 Returns driver #4 for car 711
 

Use HTTP headers for serialization formats

Both, client and server, need to know which format is used for the communication. The format has to be specified in the HTTP-Header.

Content-Type defines the request format.
Accept defines a list of acceptable response formats.

Use HATEOAS

Hypermedia as the Engine of Application State is a principle that hypertext links should be used to create a better navigation through the API.

{
  "id": 711,
  "manufacturer": "bmw",
  "model": "X5",
  "seats": 5,
  "drivers": [
   {
    "id": "23",
    "name": "Stefan Jauker",
    "links": [
     {
     "rel": "self",
     "href": "/api/v1/drivers/23"
    }
   ]
  }
 ]
}

Provide filtering, sorting, field selection and paging for collections

Filtering:

Use a unique query parameter for all fields or a query language for filtering.

GET /cars?color=red Returns a list of red cars
GET /cars?seats<=2 Returns a list of cars with a maximum of 2 seats

Sorting:

Allow ascending and descending sorting over multiple fields.

GET /cars?sort=-manufactorer,+model

This returns a list of cars sorted by descending manufacturers and ascending models.

Field selection

Mobile clients display just a few attributes in a list. They don’t need all attributes of a resource. Give the API consumer the ability to choose returned fields. This will also reduce the network traffic and speed up the usage of the API.

GET /cars?fields=manufacturer,model,id,color

Paging

Use limit and offset. It is flexible for the user and common in leading databases. The default should be limit=20 and offset=0

GET /cars?offset=10&limit=5

To send the total entries back to the user use the custom HTTP header: X-Total-Count.

Links to the next or previous page should be provided in the HTTP header link as well. It is important to follow this link header values instead of constructing your own URLs.

Link: https://yourdomain.com/sample/api/v1/cars?offset=15&limit=5; rel="next",
https://yourdomain.com/sample/api/v1/cars?offset=50&limit=3; rel="last",
https://yourdomain.com/sample/api/v1/cars?offset=0&limit=5; rel="first",
https://yourdomain.com/sample/api/v1/cars?offset=5&limit=5; rel="prev",

Version your API

Make the API Version mandatory and do not release an unversioned API. Use a simple ordinal number and avoid dot notation such as 2.5.

We are using the url for the API versioning starting with the letter "v"

/blog/api/v1

Handle Errors with HTTP status codes

It is hard to work with an API that ignores error handling. Pure returning of a HTTP 500 with a stacktrace is not very helpful.

Use HTTP status codes

The HTTP standard provides over 70 status codes to describe the return values. We don’t need them all, but there should be used at least a mount of 10.

200 - OK - Eyerything is working
201 - OK - New resource has been created
204 - OK - The resource was successfully deleted
304 - Not Modified - The client can use cached data
400 - Bad Request - The request was invalid or cannot be served. The exact error should be explained in the error payload. E.g. "The JSON is not valid"
401 - Unauthorized - The request requires an user authentication
403 - Forbidden - The server understood the request, but is refusing it or the access is not allowed.
404 - Not found - There is no resource behind the URI.
422 - Unprocessable Entity - Should be used if the server cannot process the enitity, e.g. if an image cannot be formatted or mandatory fields are missing in the payload.
500 - Internal Server Error - API developers should avoid this error. If an error occurs in the global catch blog, the stracktrace should be logged and not returned as response.

Use error payloads

All exceptions should be mapped in an error payload. Here is an example how a JSON payload should look like.

{
  "errors": [
   {
    "userMessage": "Sorry, the requested resource does not exist",
    "internalMessage": "No car found in the database",
    "code": 34,
    "more info": "http://dev.mwaysolutions.com/blog/api/v1/errors/12345"
   }
  ]
}

Allow overriding HTTP method

Some proxies support only POST and GET methods. To support a RESTful API with these limitations, the API needs a way to override the HTTP method.

Use the custom HTTP Header X-HTTP-Method-Override to overrider the POST Method.

Dynamic GridView Control in C# ASP.Net

In webapplications, one the most widely task is showing a table of information to clients. In Asp.net, we make utilization of the Datagrid, Datalist and Repeater controls. Every day, the need of showing the information will be diverse. Now, we will explain to you about "How to Create Dynamic GridView Control in C#/ASP.Net". Please read the steps carefully.

Implementing Dynamic GridView Control

Utilizing the gridview to show the articles will show the article a little in diverse layout when compared with Datalist. Appoint the below figure, Dynamic Gridview.

Constructing Dynamic GridView

Showing the articles in gridview will be different from showing in datalist. For that, i have made two Template classes :
  • DynamicGridViewTextTemplate
  • DynamicGridViewURLTemplate
Dynamicgridviewtexttemplate class is utilized to include a layout column with label while Dynamicgridviewurltemplate class is utilized to include URL of the article.

TemplateClass for GridView

public class DynamicGridViewTextTemplate : ITemplate
{
    string _ColName;
    DataControlRowType _rowType;
    int _Count;
    public DynamicGridViewTextTemplate(string ColName, DataControlRowType RowType)
    {
        _ColName = ColName;
        _rowType = RowType;
    }
    public DynamicGridViewTextTemplate(DataControlRowType RowType, int ArticleCount)
    {
        _rowType = RowType;
        _Count = ArticleCount;
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (_rowType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = "" + _ColName + "";
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:              
                 Label lbl = new Label();
                 lbl.DataBinding += new EventHandler(this.lbl_DataBind);
                 container.Controls.Add(lbl);              
                break;
            case DataControlRowType.Footer:
                Literal flc = new Literal();
                flc.Text = "Total No of Articles:" + _Count + "";
                container.Controls.Add(flc);
                break;
            default:
                break;
        }
    }
 
  
    private void lbl_DataBind(Object sender, EventArgs e)
    {
        Label lbl  = (Label)sender;
        GridViewRow row = (GridViewRow)lbl.NamingContainer;
        lbl.Text =DataBinder.Eval(row.DataItem, _ColName).ToString();
    }
 
}
public class DynamicGridViewURLTemplate : ITemplate
{
    string _ColNameText;
    string _ColNameURL;
    DataControlRowType _rowType;
 
    public DynamicGridViewURLTemplate(string ColNameText, string ColNameURL, DataControlRowType RowType)
    {
        _ColNameText = ColNameText;
        _rowType = RowType;
        _ColNameURL = ColNameURL;
    }
    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (_rowType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = "" + _ColNameURL + "";
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:
                HyperLink hpl = new HyperLink();
                hpl.Target = "_blank";
                hpl.DataBinding += new EventHandler(this.hpl_DataBind);
                container.Controls.Add(hpl);
                break;
            default:
                break;
        }
    }
 
    private void hpl_DataBind(Object sender, EventArgs e)
    {
        HyperLink hpl = (HyperLink)sender;
        GridViewRow row = (GridViewRow)hpl.NamingContainer;
        hpl.NavigateUrl = DataBinder.Eval(row.DataItem, _ColNameURL).ToString();
        hpl.Text = "
" + DataBinder.Eval(row.DataItem, _ColNameText).ToString() + "
"; } }

Using the Template Class in GridView

Utilizing dynamic template in gridview is not the same as datalist i.e. we will make the dynamic gridview in column wise with header layout, item template and footer layout from the first column till the last.

Steps:

  • Create a Gridview Object.
  • Create an instance of TemplateField object.
  • Instantiate the Dynamic template class with proper ListItemType and assign it to corresponding template property of TemplateField object and finally add this object to the column collection of GridView. Refer the below code for better understanding.

Templates of GridView

TemplateField tf = new TemplateField();
                tf.HeaderTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.Header);
                tf.ItemTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.DataRow);
                tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count); 
In the event that you analyze the usage of Datalist, in Gridview we won't make dynamic template for the grid within we make it for the grid's column (Templatefield). Appoint the below code (Using Template class) for clear understanding.

Using Template class

for (int i = 0; i < ds.Tables.Count; i++)
        {
            if (ds.Tables[i].Rows.Count > 0)
            {
                GridView gvDynamicArticle = new GridView();
                gvDynamicArticle.Width = Unit.Pixel(700);
                gvDynamicArticle.BorderWidth = Unit.Pixel(0);
                gvDynamicArticle.Caption = "
+ ds.Tables[i].Rows[0]["Category"].ToString() + " Articles
"; gvDynamicArticle.AutoGenerateColumns = false; gvDynamicArticle.ShowFooter = true; TemplateField tf = null; tf = new TemplateField(); tf.HeaderTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.Header); tf.ItemTemplate = new DynamicGridViewTextTemplate("ArticleID", DataControlRowType.DataRow); tf.FooterTemplate = new DynamicGridViewTextTemplate(DataControlRowType.Footer, ds.Tables[i].Rows.Count); gvDynamicArticle.Columns.Add(tf); tf = new TemplateField(); tf.HeaderTemplate = new DynamicGridViewTextTemplate("Title", DataControlRowType.Header); tf.ItemTemplate = new DynamicGridViewTextTemplate("Title", DataControlRowType.DataRow); gvDynamicArticle.Columns.Add(tf); tf = new TemplateField(); tf.HeaderTemplate = new DynamicGridViewTextTemplate("Description", DataControlRowType.Header); tf.ItemTemplate = new DynamicGridViewTextTemplate("Description", DataControlRowType.DataRow); gvDynamicArticle.Columns.Add(tf); tf = new TemplateField(); tf.HeaderTemplate = new DynamicGridViewURLTemplate("Title", "URL", DataControlRowType.Header); tf.ItemTemplate = new DynamicGridViewURLTemplate("Title", "URL", DataControlRowType.DataRow); gvDynamicArticle.Columns.Add(tf); tf = new TemplateField(); tf.HeaderTemplate = new DynamicGridViewTextTemplate("Author", DataControlRowType.Header); tf.ItemTemplate = new DynamicGridViewTextTemplate("CreatedBy", DataControlRowType.DataRow); gvDynamicArticle.Columns.Add(tf); gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(this.DynamicGrid_RowDataBound); gvDynamicArticle.DataSource = ds.Tables[i]; gvDynamicArticle.DataBind(); phDynamicGridHolder.Controls.Add(gvDynamicArticle); } }
In the above code (Using Template class), we can unmistakably comprehend that we are making the dynamic template for the gridview's column instead of Datalist where we made the template for the grid itself. To throw more light on this it implies that we are making the first column's header, item and footer and adding it to the gridview's column list through Templatefield article till the last column as I said before.