Sunday, September 15, 2019

throttling in WebAPI

Many API’s out there, such as GitHub’s API, have a concept called “rate limiting” or “throttling” in place. Rate limiting is used to prevent clients from issuing too many requests over a short amount of time to your API. For example, we can limit anonymous API clients to a maximum of 60 requests per hour whereas we can allow more requests to authenticated clients. 


Can someone DOS attack your API and bring down your web service? Could I hit your API at 100 requests a second and bring down your server? Or can you throttle your users like this?



What Is API Throttling?

API throttling allows you to control the way an API is used. Throttling allows you to set permissions as to whether certain API calls are valid or not. Throttles indicate a temporary state and are used to control the data that clients can access through an API. When a throttle is triggered, you can disconnect a user or just reduce the response rate. You can define a throttle at the application, API, or user level.
As a developer, you have control over what applications and which users can use your APIs. Just like permissions, a combination of multiple throttles may be used in a single request. You can even have multiple levels of throttling based on the user. For example, you can restrict sensitive information from external developers, while giving access to the same for internal developers.

Why Do You Need Throttling?

  • APIs are a gateway to your backend resources and throttling offers you an extra layer of protection for those resources.
  • You can deliver consistent applications by making sure that a single client is not suffocating your applications. Enhanced performance will drastically improve the end-user experience.
  • You can control user authentication and access by rate limiting APIs at various levels - resource, API, or application.
  • You can design a robust API that can be leveraged by multiple groups based on their access level. Simplified API monitoring and maintenance can help reduce your costs.

What Are the Types of Throttling?

Enterprises custom throttle their APIs based on the needs of their organization such as monetization, authentication, security, governance, performance, availability, etc. Here are some general throttling strategies adopted by the industry today to help you decide what your API needs:

  • Rate-Limit Throttling: This is a simple throttle that enables the requests to pass through until a limit is reached for a time interval. A throttle may be incremented by a count of requests, size of a payload, or it can be based on content; for example, a throttle can be based on order totals. This is also known as the API burst limit or the API peak limit.
  • IP-Level Throttling: You can make your API accessible only to a certain list of whitelisted IP addresses. You can also limit the number of requests sent by a certain client IP.
  • Scope Limit Throttling: Based on the classification of a user, you can restrict access to specific parts of the API - certain methods, functions, or procedures. Implementing scope limits can help you leverage the same API across different departments in the organization.
  • Concurrent Connections Limit: Sometimes your application cannot respond to more than a certain number of connections. In such cases, you need to limit the number of connections from a user/account to make sure that other users don't face a DoS (Denial of Service) error. This kind of throttling also helps secure your application against malicious cyberattacks.
  • Resource-Level Throttling (also referred to as Hard Throttling): If a certain query returns a large result set, you can throttle the request so that your SQL engine limits the number of rows returned by using conditions attributes like TOP, SKIP, SQL_ATTR_MAX_ROWS, etc.
  • Tiers of Throttling: Throttling can be applied at multiple levels in your organization:
    • API-level throttling.
    • Application-level throttling.
    • User-level throttling.
    • Account-level throttling.




REST API - Response Codes and Statuses

REST API - Response Codes and Statuses

Code
Status
Description
200
OK
The request was successfully completed.
201
Created
A new resource was successfully created.
400
Bad Request
The request was invalid.
401
Unauthorized
The request did not include an authentication token or the authentication token was expired.
403
Forbidden
The client did not have permission to access the requested resource.
404
Not Found
The requested resource was not found.
405
Method Not Allowed
The HTTP method in the request was not supported by the resource. For example, the DELETE method cannot be used with the Agent API.
409
Conflict
The request could not be completed due to a conflict. For example,  POST ContentStore Folder API cannot complete if the given file or folder name already exists in the parent location.
500
Internal Server Error
The request was not completed due to an internal error on the server side.
503
Service Unavailable
The server was unavailable.

DelegatingHandler for response in WebApi

Delegate handler use to track the incoming request in your web api project, so we register delegate handler in global.asax file after creation, it may be useful in tracking for request and response for request coming for actions.


message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.
Typically, a series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain. This pattern is called a delegating handler.

Server-Side Message Handlers

On the server side, the Web API pipeline uses some built-in message handlers:
  • HttpServer gets the request from the host.
  • HttpRoutingDispatcher dispatches the request based on the route.
  • HttpControllerDispatcher sends the request to a Web API controller.


Thursday, August 8, 2019

Routing in WebAPI?

Routing is how Web API matches a URI to an action.


It routes an incoming HTTP request to a particular action method on a Web API controller.


Web API supports two types of routing:
  1. Convention-based Routing
  2. Attribute Routing

Convention-based Routing

In the convention-based routing, Web API uses route templates to determine which controller and action method to execute. At least one route template must be added into route table in order to handle various HTTP requests.

Example:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable attribute routing
        config.MapHttpAttributeRoutes();
        
        // Add default route using convention-based routing
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}


Configure Multiple Routes

However, you can configure multiple routes in the Web API using HttpConfiguration object.


Attribute Routing

Attribute routing is supported in Web API 2. As the name implies, attribute routing uses [Route()] attribute to define routes. The Route attribute can be applied on any controller or action method.
In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling config.MapHttpAttributeRoutes() method.

Example:
public class StudentController : ApiController
{
    [Route("api/student/names")]
                public IEnumerable<string> Get()
    {
                return new string[] { "student1", "student2" };
    }
}


Thursday, July 18, 2019

What is WCF and Why We Use?

WCF stands for Windows Communication Foundation. It is basically used to create a distributed and interoperable Application.


=====================================================================
Distributed Application 

It means those Applications, which do not run only on single system but can run on multiple systems, which are connected over the network. For example, a Web Service that can consume by different clients.

Interoperable 
It means that an Application can consume or connect with another Application but it does not matter in which platform it is developed.


Why we need WCF Applications

In this, I am explaining why we need WCF Application, if we already have Web Service.

Suppose, you have two clients- one wants to use a Web Service, which sends data over the network, using Http protocol and want reply in XML format, so we will create a Web Service.

The other wants to send the data, using Web Service over the network, using TCP protocol and replying in binary format, then we need to implement a remote Web service with TCP protocol.

Problem

The problem is in the example, shown above, we need to create two different Services for two different clients .WCF is solving this problem and one single service can be consumed by two different clients- either they want same protocol or a different protocol. We specify the protocol name in an endpoint attribute of the Web Service.



Message

Message is the communication unit, as it is in the form of an envelop. The transmission of the data from the client to Service and Service to client is being done by envelop. The envelop or message has the sections, given below-
  • Header 
  • Body
By default Header and fault are disabled but Body is responsible for the data transmission or data exchanging.
Header is useful to send some data from client to Server. Suppose we want to send user name from each request but don’t want to send it by an argument, we can easily add it into message header.
Endpoint
Endpoint is a very essential part of WCF Application, as it describes the address of Web Service from where a user can receive and send the message. It also specifies the communication mechanism of how the message will be sent or received.
End point consists of three things, which are A,B,C and each of them have a question mark.
  • Address (Where?)
  • Binding (how?)
  • Contract (What?)
Endpoint = A + B+ C

Address is the address of WCF Service, where the Service is hosted? It gives the exact URL of Web Service, where the Service hosts the pattern of URL, which is-





Binding In Web API

Binding is a process to set values for the parameters when Web API calls a controller action method.


Media type formater: It is used to read or set the parameter in requested body is called 
media type formatter.

fromuri
FromBody

Web API Versioning.

 Implement the new feature without impacting the existing consumers we can solve this problem by API versioning. When the business has start...