Search This Blog

Tuesday, December 1, 2020

Q16-Q20

Q16. How to do API versioning. eg client 1 want to pass 2 parameters and client 2 want to pass 3 parameters. 
Q17. What is content negotiation in webapi? How to achieve it?
Q18How controller in mvc and webapi in .net core are different?
Q19. What is the difference between GET, POST, PUT,  DELETE, PATCH ?
Q20. What are the features of REST api?
-----------------------------------------------------------------------------------------------------------------------------
Q16. How to do API versioning. eg client 1 want to pass 2 parameters and client 2 want to pass 3 parameters. 

Answer:
There are multiple ways to handle API Versioning below are few of them. 
1. URI Path versioning
2. URI Parameter Versioning
3. Content Negotiation
4. Request Header. 

examples of URI path versioning
http://localhost:7500/api/v1/product/123
http://localhost:7500/api/v2/product/123

 URI Parameter Versioning
http://localhost:7500/api/product/123?v=1.1
http://localhost:7500/api/product/123?v=1.2

-----------------------------------------------------------------------------------------------------------------------------
Q17. What is content negotiation in webapi? How to achieve it?

Answer:
Returning of data from API into various formats is known as content negotiation. it could be json, xml, plain text etc. 

There are two main headers to achieve it. 
Content-type: They of format data in going to API. example application/json
 
AcceptThe acceptable media types for the response, such as “application/json,” “application/xml,” This is type of format client is expecting.

-----------------------------------------------------------------------------------------------------------------------------
Q18. How controller in MVC and webapi in .net core are different?

Answer:
The Controller class derives from ControllerBase and adds some members that are needed to support Views.

Controller class = ControllerBase class + view support return types. 

 In .net core MVC controller get inherited from "Controller" class which as return type as JsonResult, ViewResult, PartialResult... 

Where as webapi controller get inherited from ControllerBase. it has returntypes like ActionResult, Task <> type

-----------------------------------------------------------------------------------------------------------------------------
Q19. What is the difference between GET, POST, PUT,  DELETE, PATCH ?

Answer:
When following REST guidelines for CRUD operations we have following options. 

HTTP GET
HTTP POST
HTTP PUT
HTTP DELETE
HTTP PATCH


GET:
1.  method is used to retrieve data from a server at the specified resource. it could be /users or users/324
2. HTTP Response 200(OK) - For any given HTTP GET API, if the resource is found on the server, then it must return HTTP response code 200 (OK) – along with the response body, which is usually either XML or JSON content (due to their platform-independent nature).
3. idempotent-  Since a GET request is only requesting data and not modifying any resources, it's considered a safe and idempotent method.

Idempotence means that applying an operation once or applying it multiple times has the same effect. Examples: Multiplication by zero. No matter how many times you do it, the result is still zero.

POST:
1. POST requests are used to send data to the API server to create or update a resource.  Request body could be JSON, XML, or query parameters.
2A. HTTP response code 201 (Created) -- the response SHOULD be HTTP response code 201 (Created) and contain an entity which describes the status of the request and refers to the new resource.
2B. It will create a new identity resource if the send data doesnot exits in database.  
3. non-idempotent. It mutates data on the backend server (by creating or updating a resource), as opposed to a GET request which does not change any data.

PUT:
1. Similar to POST, PUT requests are used to send data to the API to update a resource. Usually whole object is send to request to make an update. 
2. 200, 201, 204 -- when a PUT request creates a resource the server will respond with a 201 (Created), and if the request modifies existing resource the server will return a 200 (OK) or 204 (No Content)
3. idempotent. So if you send a request multiple times, that should be equivalent to single request modification. In contrast, calling a POST request repeatedly make have side effects of creating the same resource multiple times.

The difference between the POST and PUT APIs can be observed in request URIs. POST requests are made on resource collections, whereas PUT requests are made on a single resource.

DELETE:
1. Delete the resource. 
2. 200, 202 -A successful response of DELETE requests should be HTTP response code 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has been queued
3. idempotent - DELETE operations are idempotent. If you DELETE a resource, it’s removed from the collection of resources. Repeatedly calling DELETE API on that resource will not change the outcome – however, calling DELETE on a resource a second time will return a 404 (NOT FOUND) since it was already removed

PATCH:
1. make partial update on a resource. Only partial data is sent. 
2. (Important) We must use patch in case of network utilization by sending less data over the network. So if we are using any cloud service where we are cost by network utilization we must implement PATCH. 
3. It can only modify the data and not create it, unlike PUT which can create data as well in case data not found. 



-----------------------------------------------------------------------------------------------------------------------------




-----------------------------------------------------------------------------------------------------------------------------

Q11-Q15

 Q11. How can I restrict my API methods to expose to all? I want to expose client specific api methods. 
Q12. How API asynchronous methods calls happen? what is Task keyword?
Q13. Meaning of various HTTP Status Codes?
Q14. What are the various return types of a controller action in webapi?
Q15. In case of unhandled exception, what would be the default http response code we will return?
=======================================================================
Q11. How can I restrict my API methods to expose to all? I want to expose client specific api methods. 

Answer:
Following way we can do this. 
  1. Using API key techniques. In this we have api key as per each client and API key is cross checked for each client. We can have client ids annotation on web api methods. Here only few clients are allowed. 




2. We can use cloud to restrict clients on api access. we can different methods name based on client. 

3. I can use Authenticate attribute in mvc application and using authentication filter and I can have some logic over there.  

=======================================================================
Q12. How API asynchronous methods calls happen? what is Task keyword?

Answer:
We have few Async programming pattern. 

Task based Asynchronous Pattern- 
  • The Microsoft .NET Framework 4.0 introduces a new Task Parallel Library (TPL) for parallel computing and asynchronous programming. The namespace is "System.Threading.Tasks".
  • A Task can represent an asynchronous operation and a Task provides an abstraction over creating and pooling threads.










C# 5.0 async and await based Asynchronous Pattern

  • Two new keywords, async and await, were introduced in C# 5.0 and .NET 4.5. 
  • These are implemented at the compiler level and built on top of the "System.Threading.Tasks.Task" feature of .NET 4.0.
  1. async void LoadEmployee_Click(object sender, RoutedEventArgs e) {  
  2.     // ...  
  3.     await viewer.LoadEmplployeeAsync();  
  4.     // ...  
  5. }

=======================================================================
Q13. Meaning of various HTTP Status Codes?

Answer:
2xx: Success
It means the action was successfully received, understood, and accepted.
  • 200 OK The request is OK.
  • 201 Created The request is complete, and a new resource is created .
  • 202 Accepted The request is accepted for processing, but the processing is not complete.
  • 204 No Content A status code and a header are given in the response, but there is no entity-body in the reply.
4xx: Client Error
It means the request contains incorrect syntax or cannot be fulfilled.
Check webApi #15

5xx: Server Error
It means the server failed to fulfill an apparently valid request
Check webApi #15

=======================================================================
Q14. What are the various return types of a controller action in webapi?

Answer:
The Web API action method can have following return types.
  1. Void
  2. Primitive Type/Complex Type - retun types like int, string, list<employees> etc
  3. HttpResponseMessage - HttpResponseMessage is used when we want to customize the return type (action result) of an action method. Responses are customized by providing status code, content type, and data to be returned to HttpResponseMessage.
  4. IHttpActionResult - The IHttpActionResult interface was introduced in Web API 2. Essentially, it defines an HttpResponseMessage factory.
Knowledge bomb
IHttpActionResult is a way for creating responses introduced in WebAPI2 but IActionResult is more leaned towards ASP.NET MVC for returning the result of an action method. Also IActionResult is widely used in .net Core as well.

Q15. In case of unhandled exception, what would be the default http response code we will return in webapi?

Answer:
In case of unhandled exception we will return Http: 500 Internal server error in case of error. 

  1. 400 -  Bad Request - This is the generic error that tells us someone created a bad request. Perhaps required fields are missing or header values are not filled in.
  2. 401- Unauthorized Indicates that authentication has failed. This could be because of an expired, missing, or invalid token.
  3. 403 - Forbidden - Indicates that authorization failed. Alternatively, you can also use 404 so that the consumer doesn’t know that the resource even exists.
  4. 404 - Not Found - The requested resource is not found. Companies like GitHub also use 404 if you try to access a resource that you do not have the authorization to access.
  5. 500 - Internal Server Error - When something goes wrong on the server, the consumer can’t do anything about it. Just let them know there’s a problem and that they should try again later or contact support.

Q6-Q10

Q6. Can we return view using REST webAPI?
Q7. Can we add route at run time in WEB API?
Q8. What is AntiForgery token?
Q9. How to change the name of route in webapi? Custom method names in webapi. 
Q10. How you do authentication in webapi?
-------------------------------------------------------------------------------------------------------------------------
Q6. Can we return view using REST webAPI?

Answer:
Simple answer is no. WebApi controllers returns just data. Its the MVC controller that returns View.
-------------------------------------------------------------------------------------------------------------------------
Q7. Can we add route at run time in WEB API?

Answer:
Yes. you can do by calling Configuration.Initializer(Configuration) and making changes in CustomHttpControllerSelector  class.
-------------------------------------------------------------------------------------------------------------------------
Q8. What is AntiForgery token?

Answer:
AntiForgery Token is used to avoid CSRF. Cross-Site Request Forgery (CSRF) is an attack where a malicious site sends a request to a vulnerable site where the user is currently logged in. 
-------------------------------------------------------------------------------------------------------------------------
Q9. How to change the name of route in webapi? Custom method names in webapi. 

Answer:
Change in name of route can be done at 3 level
1. global level, 
2. Controller level
  1. [RoutePrefix(“reviews”)]
3. Action level
  1. Attribute routing - [Route("api/student/names")] 
  2. Action name - [ActionName("GetEmployeeByID")] 
-------------------------------------------------------------------------------------------------------------------------
Q10. How you do authentication in webapi?

Answer:

My Other Blogs

Q1-Q5

Q1. What is content negotiation in web api?
Q2. Name one tool available to test WEBAPI?
Q3. What is OWIN hosting in WEBAPI?
Q4. Advantages of webapi 2/3 over WCF?
Q5. How routing is done in WEB API? 
--------------------------------------------------------------------------------------------------------------------------
Q1. What is content negotiation in web api?

Answer:
Accept: in header is what content negotiation works on. 

Some client machines want data in normal HTML format and some in normal text format. Others need the JSON format and still others in XML format.
The formal definition of Content Negotiation as “the process of selecting the best representation for a given response when there are multiple representations available”.

Now, the fact should be clear, “Content Negotiation” means the client and server can negotiate. It’s not always possible for the server to return data in the requested format

The question is, how does the Web API know what the clinet expects? By checking below the header of the request object.
1) Content-type: data type in which request will go from UI. eg post request
2) Accept: The acceptable media types for the response, such as “application/json,” “application/xml,” or a custom media type such as "application/vnd.example+xml".
3) Accept-Charset: The acceptable character sets, such as UTF-8 or ISO 8859-1.
4) Accept-Encoding: The acceptable content encodings, such as gzip.
5) Accept-Language: The preferred natural language, such as “en-us”.

https://www.c-sharpcorner.com/UploadFile/dacca2/understand-content-negotiation-in-web-api/
--------------------------------------------------------------------------------------------------------------------------
Q2. Name one tool available to test WEBAPI?

Answer:
Postman

--------------------------------------------------------------------------------------------------------------------------
Q3. What is OWIN hosting in WEBAPI?
Answer:
 
Open Web Interface for .NET (OWIN) decouples the web application from the server, which makes OWIN ideal for self-hosting a web application in your own process, outside of IIS

--------------------------------------------------------------------------------------------------------------------------
Q4. Advantages of webapi 2/3 over WCF?

Answer: 
Read WebAPI #25 also
  1. Webapi is Restful http calls while WCF is SOAP based xml calls. thus webapi is lighter.
  2. Comparatively WCF require more tedious and extensive configurations.
  3. Webapi usually has broad ranges of clients like browsers, mobiles phones, tablets, iPhone etc.
--------------------------------------------------------------------------------------------------------------------------
Q5. How routing is done in WEB API?

Answer:
Routing is possible in two ways in web api.
  1. by defining Routing in WebApiConfig.cs class file.
  2. by attribute routing.
    1. We also have route prefix option at controller level. [RoutePrefix(“reviews”)] . Which is ultimately part of attribute routing. 
--------------------------------------------------------------------------------------------------------------------------