Day1_Web API
Day1_Web API
Christen Zarif
OutLine
• Web API
• Content- Negotiation
• Media Type Formatter
• Post – put – delete “HttptResponseMEssage”
• Method Name :[HttpGet]- [HttpPost]
• FromBody – FromURI “Default Parameter Binding”
• Attribute Routing
outline
• Representational state transfer Architecture
• Web Services
• Rest Web Services
• API
• Web API
• ASP.Net Web API
Web Service
• A web service is a collection of open protocols and
standards used for exchanging data between
applications or systems. Software applications written
in various programming languages and running on
various platforms can use web services to exchange
data
What is a RESTful?
• REST, or REpresentational State Transfer, is an
architectural style for providing standards between
computer systems on the web, making it easier for systems
to communicate with each other.
• The REST is actually an architectural pattern that is
basically used for creating Web API’s which uses HTTP as
the communication method.
• This REST architectural pattern specifies a set of constraints
and those constraints a system should follow to be
considered as a Restful Service. The following are the
REST constraints
• For More
RESTful Constraints?
• Client-Server Constraint
– In the REST architectural style, the implementation of
the client and the implementation of the server can be
done independently without each knowing about the
other.
– This means that the code on the client side can be
changed at any time without affecting the operation of
the server, and the code on the server side can be
changed without affecting the operation of the client.
• Request Header :
– Contains additional information about the request ,
Example : what type of response is required (Content-Type,Accept)
• Request Body :
– Contains the data to send to the server
• Response Body :
– Contains the data send as response from the server
Http Header
Http Body
Http Requests and Responses
(Con.)
• Http Response
Status Code
Description
Http Header
Http Body
HTTP Header Fields
• HTTP Header Fields define parameters for the HTTP
operation
• Around that line are Content-Type, Content-Length,
and a few others. Each of them is a so-called HTTP
Header Field.
• These fields exist in both requests and responses.
Most of them differ for requests and responses, but
some , such as content-type, exist on both sides of the
HTTP protocol.
Use HTTP Response Codes to
Indicate Status
• 200 OK : General success status code. This is the most common code. Used to indicate success.
• 201 CREATED : Successful creation occurred (via either POST or PUT). Set the Location header to
contain a link to the newly-created resource (on POST). Response body content may or may not be
present.
• 204 NO CONTENT : Indicates success but nothing is in the response body, often used for DELETE and
PUT operations.
• 400 BAD REQUEST : General error for when fulfilling the request would cause an invalid state. Domain
validation errors, missing data, etc. are some examples.
• 401 UNAUTHORIZED : Error code response for missing or invalid authentication token.
• 403 FORBIDDEN : Error code for when the user is not authorized to perform the operation or the
resource is unavailable for some reason (e.g. time constraints, etc.).
• 404 NOT FOUND : Used when the requested resource is not found, whether it doesn't exist or if there
was a 401 or 403 that, for security reasons, the service wants to mask.
• 405 METHOD NOT ALLOWED : Used to indicate that the requested URL exists, but the requested
HTTP method is not applicable. For example, POST /users/12345 where the API doesn't support creation
of resources this way (with a provided ID). The Allow HTTP header must be set when returning a 405
to indicate the HTTP methods that are supported. In the previous case, the header would look like
"Allow: GET, PUT, DELETE"
• 409 CONFLICT : Whenever a resource conflict would be caused by fulfilling the request. Duplicate
entries, such as trying to create two customers with the same information, and deleting root objects when
cascade-delete is not supported are a couple of examples.
• 500 INTERNAL SERVER ERROR : Never return this intentionally. The general catch-all error when
the server-side throws an exception. Use this only for errors that the consumer cannot address from their
end.
Internet Media Types
• “text/html” is an identifier for a file format on the
Internet
Methods that do
not start with an
HTTP verb then
you can apply the
appropriate http
verb attribute on
the method
Action Method Naming
Conventions
HTTP Request
Method Possible Web API Action Method Name Usage
GET Get() | get() | GET() | GetAllStudent() Retrieves data.
*any name starting with Get *
POST Post() | post() | POST() | PostNewStudent() Inserts new record.
*any name starting with Post*
PUT Put() | put() | PUT() | PutStudent() Updates existing
*any name starting with Put* record.
PATCH Patch() | patch() | PATCH() | PatchStudent() Updates record
*any name starting with Patch* partially.
DELETE Delete() | delete() | DELETE() | DeleteStudent() Deletes record.
*any name starting with Delete*
Web API Controller(cont.)
•
MVC & Web API Controller
• Followings are valid HTTP GET Requests for the above action
method.
– http://localhost/api/student?id=1
– http://localhost/api/student?ID=1
Web API Parameter
Binding(cont.)
• POST Action Method with Primitive Parameter
• HTTP POST request is used to create new resource. It can
include request data into HTTP request body and also in query
string.
• Consider the following Post action method.
•
Web API Parameter
Binding(cont.)
• Bowser only support GET() verbs so now we will use
postman.
• As you can see above, Post() action method includes primitive
type parameters id and name. So, by default, Web API will get
values from the query string. For example, if an HTTP POST
request
is http://localhost/api/student?id=1&name=steve then the
value of id will be 1 and name will be "steve" in the above
Post() method.
Web API Parameter
Binding(cont.)
• Bowser only support GET() verbs so now we will use
postman.
Web API Parameter
Binding(cont.)
• Now, consider the following Post() method with complex type
parameter.
Web API Parameter
Binding(cont.)
• In postman
• 1-Set content-type of the request to application/json
•
Web API Parameter
Binding(cont.)
• In postman
• 2-pass the object in the body raw
•
Web API Parameter
Binding(cont.)
• In postman
• 3-The action look like the following
•
Web API Parameter
Binding(cont.)
• [FromUri] and [FromBody]
• You have seen that by default Web API gets the value of a
primitive parameter from the query string and complex type
parameter from the request body.
• But, what if we want to change this default behaviour?
• Use [FromUri] attribute to force Web API to get the value of
complex type from the query string and
• [FromBody] attribute to get the value of primitive type from
the request body, opposite to the default rules.
Web API Parameter
Binding(cont.)
• [FromUri] and [FromBody]
• For example, consider the following Get method.
Web API Parameter
Binding(cont.)
• [FromUri] and [FromBody]
• In the above example, Get method includes complex type
parameter with [FromUri] attribute. So, Web API will try to
get the value of Student type parameter from the query string.
• For example, if an HTTP GET
request http://localhost:xxxx/api/student?id=1&name=steve
then Web API will create Student object and set its id and
name property values to the value of id and name query string
Web API Parameter
Binding(cont.)
• [FromUri] and [FromBody]
Media Type:
• Media type (aka MIME type) specifies the format of the data
as type/subtype e.g. text/html, text/xml, application/json,
image/jpeg etc.
Web API Request/Response Data
Formats(cont.)
• In HTTP request, MIME type is specified in the request
header using Accept and Content-Type attribute.
• The Accept header attribute specifies the format of response
data which the client expects and the
• Content-Type header attribute specifies the format of the data
in the request body so that receiver can parse it into
appropriate format.
• For example, if a client wants response data in JSON format
then it will send following GET HTTP request with Accept
header to the Web API.
Web API Request/Response Data
Formats(cont.)
• The same way, if a client includes JSON data in the request
body to send it to the receiver then it will send following
POST HTTP request with Content-Type header with JSON
data in the body.
ASP.NET Web API: Media-Type
Formatters
• As you have seen in the previous section that Web API
handles JSON and XML formats based on Accept and
Content-Type headers.
• But, how does it handle these different formats? The
answer is: By using Media-Type formatters.
• Request Headers
The Request header parameter specifies which Request
headers are allowed. To allow any header set value to "*"
•
What is CORS?(cont.)
• Using JSONP(JSON with Padding) formatter
• Using Microsoft.AspNet.WebApi.Cors
• HTTP Methods
The methods parameter specifies which HTTP methods are
allowed to access the resource.
• Use comma-separated values when you have multiple HTTP
methods like "get,put,post". To allow all HTTP methods, use
the wildcard value "*".
•
What is CORS?(cont.)
• Using JSONP(JSON with Padding) formatter
• Using Microsoft.AspNet.WebApi.Cors
• Then add the following code to register method in
WebApiConfig.cs