50% found this document useful (2 votes)
534 views

API Testing Document

API testing involves testing application programming interfaces (APIs). There are different protocols that can be used for API testing, including SOAP, REST, HTTP, UDDI, and JMS. The most common protocols are SOAP and REST. SOAP uses XML and is slower, while REST supports different data formats like JSON and XML, supports caching, and is faster. Content negotiation allows REST APIs to return resource representations in different formats like JSON or XML based on client requests.

Uploaded by

sanchi rajput
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
50% found this document useful (2 votes)
534 views

API Testing Document

API testing involves testing application programming interfaces (APIs). There are different protocols that can be used for API testing, including SOAP, REST, HTTP, UDDI, and JMS. The most common protocols are SOAP and REST. SOAP uses XML and is slower, while REST supports different data formats like JSON and XML, supports caching, and is faster. Content negotiation allows REST APIs to return resource representations in different formats like JSON or XML based on client requests.

Uploaded by

sanchi rajput
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

API Testing

What is an API?

An API (Application Programming Interface) is a medium with the help of which two
applications interact with each other.

For example: Google Maps API, Amazon Advertising API, Twitter API, YouTube API, etc.

What are main differences between API and Web Service?

WEB SERVICE API

All web services are APIs. All APIs are not web services.

It can only be hosted on IIS. It can be hosted within an application or IIS.

It is not open source but can be used by any It is open source and it can be used by any client
client that understands XML. that understands JSON or XML.

It requires a SOAP protocol to receive and It is light-weight architecture and good for
send data over the network, so it is not light- devices which have limited bandwidth, like
weight architecture. mobile devices.

A Web service uses only three styles of use:


API may use any style of communication.
SOAP, REST and XML-RPC for communication.

It supports the HTTP protocol: URL,


It only supports the HTTP protocol. Request/Response Headers, caching, versioning,
content formats.
Some common protocols used in API testing?

Many protocols are now available to be used in API testing, such as JMS, REST, HTTP,
UDDI and SOAP.

SOAP:

1. SOAP is a protocol through which two computers communicate by sharing XML


document

2. SOAP supports only XML format

3. SOAP does not support caching

4. SOAP is slower than REST

5. SOAP is like custom desktop application, closely connected to the server

6. SOAP runs on HTTP but envelopes the message

REST:

1. REST is a service architecture and design for network-based software architecture

2. REST supports different data formats

3. REST supports caching

4. REST is faster than SOAP

5. REST client is just like a browser and uses standard methods An application has to fit
inside it

6. REST uses the HTTP headers to hold meta information


What is REST?

REST (Representational State Transfer) which uses HTTP protocol as a medium of


communication between the client and the server.

In REST architecture, a REST Server provides access to resources and REST client
accesses and makes these resources available. Here, each resource is identified by URIs
or global IDs, and REST uses multiple ways to represent a resource, such as text, JSON,
and XML. XML and JSON are nowadays the most popular representations of resources.

What is a “Resource” in REST?

REST architecture treats any content as a resource, which can be text files, HTML pages,
images, videos or dynamic business information.
REST Server gives access to resources and modifies them, where each resource is
identified by URIs/ global IDs.

What is the most popular way to represent a resource in REST?

REST uses different representations to define a resource like text, JSON, and XML.

XML and JSON are the most popular representations of resources.

What is messaging in Restful Web services?

Restful web services use the HTTP protocol as a communication tool between the client
and the server. The technique that when the client sends a message in the form of an
HTTP Request, the server sends back the HTTP reply is called Messaging. These
messages comprise message data and metadata, that is, information on the message
itself.
What are the core components of an HTTP request?

An HTTP request contains five key elements:

 An action showing HTTP methods like GET, PUT, POST, DELETE.


 Uniform Resource Identifier (URI), which is the identifier for the resource on the
server.
 HTTP Version, which indicates HTTP version, for example-HTTP v1.1.
 Request Header, which carries metadata (as key-value pairs) for the HTTP Request
message. Metadata could be a client (or browser) type, format supported by the
client, format of a message body format, cache settings, and so on.
 Request Body, which indicates the message content or resource representation.

Caching in Rest API’s

 Caching is the ability to store copies of frequently accessed data in several places
along the request-response path. When a consumer requests a resource
representation, the request goes through a cache or a series of caches (local cache,
proxy cache or reverse proxy) toward the service hosting the resource. If any of the
caches along the request path has a fresh copy of the requested representation, it
uses that copy to satisfy the request. If none of the caches can satisfy the request,
the request travels all the way to the service (or origin server as it is formally known).
 Using HTTP headers, an origin server indicates whether a response can be cached
and if so, by whom, and for how long. Caches along the response path can take a
copy of a response, but only if the caching metadata allows them to do so.
 Being cacheable is one of architectural constraints of REST. GET requests should be
cachable by default – until special condition arises. Usually, browsers treat all GET
requests cacheable. POST requests are not cacheable by default but can be made
cacheable if either an Expires header or a Cache-Control header with a directive, to
explicitly allows caching, is added to the response. Responses
to PUT and DELETE requests are not cacheable at all.

Compression in Rest
REST APIs can return the resource representations in a number of formats such as XML,
JSON, HTML or even plain text. All such forms can be compressed to a lesser number of
bytes to save bandwidth over the network. Different protocols use different techniques
to enable compression and notify the clients about compression scheme – so that client
can decompress it before consuming the representations.

Compression Related Request/Response Headers

Accept-Encoding

While requesting resource representations – along with an HTTP request the client
sends an Accept-Encoding header that says what kind of compression algorithms the
client understands.

The two standard values for Accept-Encoding are compress and gzip.


A sample request with accept-encoding header looks like this :
GET /employees HTTP/1.1
Host: www.domain.com
Accept: text/html
Accept-Encoding: gzip,compress
Other possible usage of accept-encoding may be:

Accept-Encoding: compress, gzip


Accept-Encoding:
Accept-Encoding: *
Accept-Encoding: compress;q=0.5, gzip;q=1.0
Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0

If an Accept-Encoding field is present in a request, and if the server cannot send a


response which is acceptable according to the Accept-Encoding header, then the server
SHOULD send an error response with the 406 (Not Acceptable) status code.

Content-Encoding
If the server understands one of the compression algorithms from Accept-Encoding, it
can use that algorithm to compress the representation before serving it. When
successfully compressed, server lets know the client of encoding scheme by another
HTTP header i.e. Content-Encoding.
200 OK
Content-Type: text/html
Content-Encoding: gzip
If the content-coding of an entity in a request message is not acceptable to the origin
server, the server SHOULD respond with a status code of 415 (Unsupported Media
Type). If multiple encodings have been applied to an entity, the content encodings
MUST be listed in the order in which they were applied.

Please note that original media-type for request and response are not impacted
whether compression is requested or not.

Compression can save a lot of bandwidth, with very little cost in additional complexity.
Also, you may know that most web browsers automatically request compressed
representations from website host servers – using above headers.

REST – Content Negotiation


Generally, resources can have multiple presentations, mostly because there may be
multiple different clients expecting different representations. Asking for a suitable
presentation by a client, is referred as content negotiation.

Server-driven Vs Agent-driven Content Negotiation

If the selection of the best representation for a response is made by an algorithm


located at the server, it is called server-driven negotiation. If that selection is made at
agent or client side, its called agent-driven content negotiation.

Practically, you will NOT find much usage of server side negotiations because in that
way, you have to make lots of assumptions about client expectations. Few things like
client context or how client will use the resource representation is almost impossible to
determine. Apart from that this approach makes the server side code complex,
unnecessarily.

So, most REST API implementations rely on agent driven content negotiations. Agent
driven content negotiation rely on usage of HTTP request headers or resource URI
patterns.

1. Content negotiation using HTTP headers

At server side, an incoming request may have an entity attached to it. To determine
it’s type, server uses the HTTP request header Content-Type. Some common
examples of content types are “text/plain”, “application/xml”, “text/html”,
“application/json”, “image/gif”, and “image/jpeg”.
Content-Type: application/json

Similarly, to determine what type of representation is desired at client side, HTTP


header ACCEPT is used. It will have one of the values as mentioned for Content-
Type above.
Accept: application/json

Generally, if no Accept header is present in the request, the server can send pre-
configured default representation type.
Implementing Accept header based content negotiation is most used and
recommened way.

2. Content negotiation using URL patterns

Another way to pass content type information to server, client may use specific
extension in resource URIs. For example, a client can ask for details using:

http://rest.api.com/v1/employees/20423.xml
http://rest.api.com/v1/employees/20423.json
In above case, first request URI will return a XML response whether second request
URI will return a JSON response.
Defining preferences

If is possible to have multiple values in Accept header. Client may want to give multiple
values in accept header when client is not sure about if its desired representation is
present or supported by server at that time.
For example,

Accept: application/json,application/xml;q=0.9,*/*;q=0.8
Above Accept header allows you to ask the server a JSON format. If it can’t, perhaps it
could return XML format (the second level). If it’s still not possible, let it return what it
can.
The preference order is defined through the q parameter with values from 0 to 1. When
nothing is specified, the implicit value is 1.

Idempotent REST APIs


In the context of REST APIs, when making multiple identical requests has the same
effect as making a single request – then that REST API is called idempotent.

When you design REST APIs, you must realize that API consumers can make mistakes.
They can write client code in such a way that there can be duplicate requests as well.
These duplicate requests may be unintentional as well as intentional some time (e.g.
due to timeout or network issues). You have to design fault-tolerant APIs in such a way
that duplicate requests do not leave the system unstable.

An idempotent HTTP method is an HTTP method that can be called many times without
different outcomes. It would not matter if the method is called only once, or ten times
over. The result should be the same. It essentially means that the result of a successfully
performed request is independent of the number of times it is executed. For example, in
arithmetic, adding zero to a number is idempotent operation.

If you follow REST principles in designing API, you will have automatically idempotent
REST APIs for GET, PUT, DELETE, HEAD, OPTIONS and TRACE HTTP methods.
Only POST APIs will not be idempotent.
1. POST is NOT idempotent.
2. GET, PUT, DELETE, HEAD, OPTIONS and TRACE are idempotent.
Let’s analyze how above HTTP methods end up being idempotent – any why POST is not.

HTTP POST

Generally – not necessarily – POST APIs are used to create a new resource on server. So
when you invoke the same POST request N times, you will have N new resources on the
server. So, POST is not idempotent.

HTTP GET, HEAD, OPTIONS and TRACE

GET, HEAD, OPTIONS and TRACE methods NEVER change the resource state on server.


They are purely for retrieving the resource representation or meta data at that point of
time. So invoking multiple requests will not have any write operation on server, so GET,
HEAD, OPTIONS and TRACE are idempotent.

HTTP PUT

Generally – not necessarily – PUT APIs are used to update the resource state. If you
invoke a PUT API N times, the very first request will update the resource; then rest N-1
requests will just overwrite the same resource state again and again – effectively not
changing anything. Hence, PUT is idempotent.

HTTP DELETE

When you invoke N similar DELETE requests, first request will delete the resource and
response will be 200 (OK) or 204 (No Content). Other N-1 requests will return 404 (Not
Found). Clearly, the response is different from first request, but there is no change of
state for any resource on server side because original resource is already deleted.
So, DELETE is idempotent.
Please keep in mind if some systems may have DELETE APIs like this:

DELETE /item/last

In the above case, calling operation N times will delete N resources – hence DELETE is
not idempotent in this case. In this case, a good suggestion might be to change above
API to POST – because POST is not idempotent.
POST /item/last
Statelessness

As per the REST (REpresentational “State” Transfer) architecture, the server does not


store any state about the client session on the server side. This restriction is
called Statelessness. Each request from the client to server must contain all of the
information necessary to understand the request, and cannot take advantage of any
stored context on the server. Session state is therefore kept entirely on the client. Client
is responsible for storing and handling all application state related information on
client side.

It also means that the client is responsible for sending any state information to the
server whenever it is needed. There should not be any session affinity or sticky
sessions on server.

Statelessness means that every HTTP request happens in complete isolation. When the
client makes an HTTP request, it includes all information necessary for the server to fulfill
that request. The server never relies on information from previous requests. If that
information was important, the client would have sent it again in this request.

To enable clients to access these stateless APIs, it is necessary that servers also should
include every piece of information that the client may need to create the state on its
side.

For becoming stateless, do not store even authentication/authorization details of client.


Provide credentials with the request. Each request MUST stand alone and should not be
affected by the previous conversation happened from the same client in past.

Application State vs Resource State

Please do not confuse between application state and resource state. Both are
completely different things.

Application state is server-side data which servers store to identify incoming client
requests, their previous interaction details, and current context information.
Resource state is the current state of a resource on a server at any point of time – and it
has nothing to do with the interaction between client and server. It is what you get as a
response from the server as API response. You refer to it as resource representation.

REST statelessness means being free on application state.

Advantages of Statelessness

There are some very noticeable advantages for having REST APIs stateless.

1. Statelessness helps in scaling the APIs to millions of concurrent users by deploying


it to multiple servers. Any server can handle any request because there is no
session related dependency.

2. Being stateless makes REST APIs less complex – by removing all server-side state
synchronization logic.

3. A stateless API is also easy to cache as well. A specific software can decide
whether or not to cache the result of an HTTP request just by looking at that one
request. There’s no nagging uncertainty that state from a previous request might
affect the cacheability of this one. It improves the performance of applications.

4. The server never loses track of “where” each client is in the application because
the client sends all necessary information with each request.

Can GET request to be used instead of PUT to create a resource?

The PUT or POST method should be used to create a resource. GET is only used to
request data from a specified resource.
Is there any difference between PUT and POST operations?

PUT POST

PUT method requests for the enclosed entity


The POST method is used to request that
be stored under the supplied Request-URI. If
the origin server accept the entity
the Request-URI refers to an already existing
enclosed in the request as a new
resource – an update operation will happen,
subordinate of the resource identified by
otherwise create operation should happen if
the Request-URI in the Request-Line. It
Request-URI is a valid resource URI (assuming
essentially means that POSTrequest-URI
client is allowed to determine resource
should be of a collection URI.
identifier).
POST /questions
PUT /questions/{question-id}
POST is NOT idempotent. So if you retry
PUT method is idempotent. So if you send
the request N times, you will end up
retry a request multiple times, that should be
having N resources with N different URIs
equivalent to single request modification.
created on server.

Use PUT when you want to modify a singular Use POST when you want to add a child

resource which is already a part of resources resource under resources collection.

collection. PUT replaces the resource in its

entirety. Use PATCH if request updates part of


the resource.

Responses to this method are

not cacheable, unless the response

includes appropriate Cache-Control or


Though PUT is idempotent, we shall not cache
Expires header fields. However, the 303
its response.
(See Other) response can be used to

direct the user agent to retrieve a

cacheable resource.

Generally, in practice, always use PUT for


Always use POST for CREATE operations.
UPDATE operations.

Which purpose does the OPTIONS method serve for the Restful Web services?

The OPTIONS Method lists down all the operations of a web service supports. It creates
read-only requests to the server.

What is URI? What is the main purpose of REST-based web services and what is its
format?

URI stands for Uniform Resource Identifier. It is a string of characters designed for
unambiguous identification of resources and extensibility via the URI scheme.

The purpose of a URI is to locate a resource(s) on the server hosting of the web service.
A URI’s format is <protocol>://<service-name>/<ResourceType>/<ResourceID>. 

What is payload in Restful Web services?

The “payload” is the data you are interested in transporting. This is differentiated from
the things that wrap the data for transport like the HTTP/S Request/Response headers,
authentication, etc.

What is the upper limit for a payload to pass in the POST method?

<GET> appends data to the service URL. But, its size shouldn’t exceed the maximum URL
length. However, <POST> doesn’t have any such limit.

So, theoretically, a user can pass unlimited data as the payload to POST method. But, if
we consider a real use case, then sending POST with large payload will consume more
bandwidth. It’ll take more time and present performance challenges to your server.
Hence, a user should take action accordingly.

HTTP Methods
RESTful APIs enable you to develop any kind of web application having all possible CRUD
(create, retrieve, update, delete) operations. REST guidelines suggest using a specific
HTTP method on a specific type of call made to the server (though technically it is
possible to violate this guideline, yet it is highly discouraged).

Use below-given information to find suitable HTTP method for the action performed by
API.

HTTP GET

Use GET requests to retrieve resource representation/information only – and not to


modify it in any way. As GET requests do not change the state of the resource, these are
said to be safe methods. Additionally, GET APIs should be idempotent, which means
that making multiple identical requests must produce the same result every time until
another API (POST or PUT) has changed the state of the resource on the server.

If the Request-URI refers to a data-producing process, it is the produced data which shall
be returned as the entity in the response and not the source text of the process, unless
that text happens to be the output of the process.

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 response body which is usually either XML or
JSON content (due to their platform independent nature).
In case resource is NOT found on server then it must return HTTP response code 404
(NOT FOUND). Similarly, if it is determined that GET request itself is not correctly
formed then server will return HTTP response code 400 (BAD REQUEST).

Example request URIs

 HTTP GET http://www.appdomain.com/users

 HTTP GET http://www.appdomain.com/users?size=20&page=5

 HTTP GET http://www.appdomain.com/users/123

 HTTP GET http://www.appdomain.com/users/123/address

HTTP POST

Use POST APIs to create new subordinate resources, e.g. a file is subordinate to a
directory containing it or a row is subordinate to a database table. Talking strictly in
terms of REST, POST methods are used to create a new resource into the collection of
resources.

Ideally, if a resource has been created on the origin server, 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, and a Location header.
Many times, the action performed by the POST method might not result in a resource
that can be identified by a URI. In this case, either HTTP response code 200 (OK) or 204
(No Content) is the appropriate response status.
Responses to this method are not cacheable, unless the response includes
appropriate Cache-Controlor Expires header fields.
Please note that POST is neither safe nor idempotent and invoking two identical POST
requests will result in two different resources containing the same information (except
resource ids).

Example request URIs

 HTTP POST http://www.appdomain.com/users

 HTTP POST http://www.appdomain.com/users/123/accounts

HTTP PUT

Use PUT APIs primarily to update existing resource (if the resource does not exist then
API may decide to create a new resource or not). If a new resource has been created by
the PUT API, the origin server MUST inform the user agent via the HTTP response
code 201 (Created) response and if an existing resource is modified, either the 200
(OK) or 204 (No Content) response codes SHOULD be sent to indicate successful
completion of the request.
If the request passes through a cache and the Request-URI identifies one or more
currently cached entities, those entries SHOULD be treated as stale. Responses to this
method are not cacheable.

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 an
individual resource.

Example request URIs

 HTTP PUT http://www.appdomain.com/users/123

 HTTP PUT http://www.appdomain.com/users/123/accounts/456

HTTP DELETE

As the name applies, DELETE APIs are used to delete resources (identified by the
Request-URI).
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, or 204 (No Content) if the action has been performed but the response
does not include an entity.
DELETE operations are idempotent. If you DELETE a resource, it’s removed from the
collection of resource. 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. Some may argue that it makes DELETE
method non-idempotent. It’s a matter of discussion and personal opinion.

If the request passes through a cache and the Request-URI identifies one or more
currently cached entities, those entries SHOULD be treated as stale. Responses to this
method are not cacheable.

Example request URIs

 HTTP DELETE http://www.appdomain.com/users/123

 HTTP DELETE http://www.appdomain.com/users/123/accounts/456

HTTP PATCH

HTTP PATCH requests are to make partial update on a resource. If you see PUT requests
also modify a resource entity so to make more clear – PATCH method is the correct
choice for partially updating an existing resource and PUT should only be used if you’re
replacing a resource in its entirety.

Please note that there are some challenges if you decide to use PATCH APIs in your
application:

 Support for PATCH in browsers, servers, and web application frameworks is not
universal. IE8, PHP, Tomcat, Django, and lots of other software has missing or
broken support for it.

 Request payload of PATCH request is not straightforward as it is for PUT request.


e.g.

HTTP GET /users/1


produces below response:

{id: 1, username: 'admin', email: 'email@example.org'}


A sample patch request to update the email will be like this:

HTTP PATCH /users/1


[
{ “op”: “replace”, “path”: “/email”, “value”: “new.email@example.org” }
]

There may be following possible operations are per HTTP specification.

[
{ "op": "test", "path": "/a/b/c", "value": "foo" },
{ "op": "remove", "path": "/a/b/c" },
{ "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
{ "op": "replace", "path": "/a/b/c", "value": 42 },
{ "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
{ "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
]
PATCH method is not a replacement for the POST or PUT methods. It applies a delta
(diff) rather than replacing the entire resource.

Glossary

Safe Methods

As per HTTP specification, the GET and HEAD methods should be used only for retrieval
of resource representations – and they do not update/delete the resource on the
server. Both methods are said to be considered “safe“.

This allows user agents to represent other methods, such as POST, PUT and DELETE, in a
special way, so that the user is made aware of the fact that a possibly unsafe action is
being requested – and they can update/delete the resource on server and so should be
used carefully.
Idempotent Methods

The term idempotent is used more comprehensively to describe an operation that will
produce the same results if executed once or multiple times. This is a very useful
property in many situations, as it means that an operation can be repeated or retried as
often as necessary without causing unintended effects. With non-idempotent
operations, the algorithm may have to keep track of whether the operation was already
performed or not.

In HTTP specification, The methods GET, HEAD, PUT and DELETE are declared
idempotent methods. Other methods OPTIONS and TRACE SHOULD NOT have side
effects so both are also inherently idempotent.

What Is WSDL

 WSDL stands for Web Service Description Language.


 WSDL is an XML based document that provides technical details about the web
service.
 Some of the useful information in WSDL document are: method name, port types,
service end point, binding, method parameters etc.

What are different components of WSDL?


Some of the different tags in WSDL xml are:
 xsd: import namespace and schema Location: provides WSDL URL and unique
namespace for web service.
 message: for method arguments
 part: for method argument name and type
 portType: service name, there can be multiple services in a wsdl document.
 operation: contains method name
 soap: address for endpoint URL.

Authentication Types:

Http basic Access authentication: Requires username and password. Transmitted in the
header of http request.
Disadvantage: Not secured as user data is weakly encoded.

Oauth 1.0: works with tokens. Token is a unique string.

Ouath 2.0: upgrade to Oauth1.0. Provides greater security as compared to Oauth 1.0.

What is Content-Type

 Content-Type header is used to indicate the media type of the resource.


 In response it tells the client what the content type of the returned content actually
is in request such as (post or put).

Types:
1. Text/html: body content is html.
2. Multipart/formdata: is used to submit forms that contains files, non-ascii data
and binary data.
3. Message/partial: broke larger message into smaller.
4. Image/png: body content is .png image
5. Audio/mpeg: body content is mp3 or mpeg video.
6. Video/mp4: body content is mp4 video.
7. Application/json: body content is json format.
Application/x-www-form-urlencoded: is insufficient for sending large quantity of
data or text containing non-ascii char.

HTTP Status Codes


REST APIs use the Status-Line part of an HTTP response message to inform clients of
their request’s overarching result. RFC 2616 defines the Status-Line syntax as shown
below:

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF


HTTP defines forty standard status codes that can be used to convey the results of a
client’s request. The status codes are divided into the five categories presented below.

CATEGORY DESCRIPTION
1xx:
Communicates transfer protocol-level information.
Informational

2xx: Success Indicates that the client’s request was accepted successfully.

Indicates that the client must take some additional action in order to
3xx: Redirection
complete their request.

4xx: Client Error This category of error status codes points the finger at clients.

5xx: Server Error The server takes responsibility for these error status codes.

Now look at subset of codes that specially apply to the design of a REST APIs – in some
more detail.

200 (OK)

It indicates that the REST API successfully carried out whatever action the client
requested, and that no more specific code in the 2xx series is appropriate.

Unlike the 204 status code, a 200 response should include a response body.The
information returned with the response is dependent on the method used in the
request, for example:

 GET an entity corresponding to the requested resource is sent in the response;

 HEAD the entity-header fields corresponding to the requested resource are sent
in the response without any message-body;

 POST an entity describing or containing the result of the action;

 TRACE an entity containing the request message as received by the end server.

201 (Created)

A REST API responds with the 201 status code whenever a resource is created inside a
collection. There may also be times when a new resource is created as a result of some
controller action, in which case 201 would also be an appropriate response.
The newly created resource can be referenced by the URI(s) returned in the entity of the
response, with the most specific URI for the resource given by a Location header field.

The origin server MUST create the resource before returning the 201 status code. If the
action cannot be carried out immediately, the server SHOULD respond with 202
(Accepted) response instead.

202 (Accepted)

A 202 response is typically used for actions that take a long while to process. It indicates
that the request has been accepted for processing, but the processing has not been
completed. The request might or might not be eventually acted upon, or even maybe
disallowed when processing occurs.

Its purpose is to allow a server to accept a request for some other process (perhaps a
batch-oriented process that is only run once per day) without requiring that the user
agent’s connection to the server persist until the process is completed.

The entity returned with this response SHOULD include an indication of the request’s
current status and either a pointer to a status monitor (job queue location) or some
estimate of when the user can expect the request to be fulfilled.

204 (No Content)

The 204 status code is usually sent out in response to a PUT, POST, or DELETE request
when the REST API declines to send back any status message or representation in the
response message’s body.
An API may also send 204 in conjunction with a GET request to indicate that the
requested resource exists, but has no state representation to include in the body.

If the client is a user agent, it SHOULD NOT change its document view from that which
caused the request to be sent. This response is primarily intended to allow input for
actions to take place without causing a change to the user agent’s active document
view, although any new or updated meta information SHOULD be applied to the
document currently in the user agent’s active view.

The 204 response MUST NOT include a message-body and thus is always terminated by
the first empty line after the header fields.
301 (Moved Permanently)

The 301 status code indicates that the REST API’s resource model has been significantly
redesigned and a new permanent URI has been assigned to the client’s requested
resource. The REST API should specify the new URI in the response’s Location header
and all future requests should be directed to the given URI.

You will hardly use this response code in your API as you can always use the API
versioning for new API while retaining the old one.

302 (Found)

The HTTP response status code 302 Found is a common way of performing URL
redirection. An HTTP response with this status code will additionally provide a URL in
the location header field. The user agent (e.g. a web browser) is invited by a response
with this code to make a second, otherwise identical, request to the new URL specified
in the location field.

Many web browsers implemented this code in a manner that violated this standard,
changing the request type of the new request to GET, regardless of the type employed
in the original request (e.g. POST). RFC 1945 and RFC 2068 specify that the client is not
allowed to change the method on the redirected request. The status codes 303 and 307
have been added for servers that wish to make unambiguously clear which kind of
reaction is expected of the client.

303 (See Other)

A 303 response indicates that a controller resource has finished its work, but instead of
sending a potentially unwanted response body, it sends the client the URI of a response
resource. This can be the URI of a temporary status message, or the URI to some already
existing, more permanent, resource.

Generally speaking, the 303 status code allows a REST API to send a reference to a
resource without forcing the client to download its state. Instead, the client may send a
GET request to the value of the Location header.

The 303 response MUST NOT be cached, but the response to the second (redirected)
request might be cacheable.
304 (Not Modified)

This status code is similar to 204 (“No Content”) in that the response body must be
empty. The key distinction is that 204 is used when there is nothing to send in the body,
whereas 304 is used when the resource has not been modified since the version
specified by the request headers If-Modified-Since or If-None-Match.

In such case, there is no need to retransmit the resource since the client still has a
previously-downloaded copy.

Using this saves bandwidth and reprocessing on both the server and client, as only the
header data must be sent and received in comparison to the entirety of the page being
re-processed by the server, then sent again using more bandwidth of the server and
client.

307 (Temporary Redirect)

A 307 response indicates that the REST API is not going to process the client’s request.
Instead, the client should resubmit the request to the URI specified by the response
message’s Location header. However, future requests should still use the original URI.

A REST API can use this status code to assign a temporary URI to the client’s requested
resource. For example, a 307 response can be used to shift a client request over to
another host.

The temporary URI SHOULD be given by the Location field in the response. Unless the
request method was HEAD, the entity of the response SHOULD contain a short
hypertext note with a hyperlink to the new URI(s). If the 307 status code is received in
response to a request other than GET or HEAD, the user agent MUST NOT automatically
redirect the request unless it can be confirmed by the user, since this might change the
conditions under which the request was issued.

400 (Bad Request)

400 is the generic client-side error status, used when no other 4xx error code is
appropriate. Errors can be like malformed request syntax, invalid request message
parameters, or deceptive request routing etc.

The client SHOULD NOT repeat the request without modifications.


401 (Unauthorized)

A 401 error response indicates that the client tried to operate on a protected resource
without providing the proper authorization. It may have provided the wrong credentials
or none at all. The response must include a WWW-Authenticate header field containing
a challenge applicable to the requested resource.

The client MAY repeat the request with a suitable Authorization header field. If the
request already included Authorization credentials, then the 401 response indicates that
authorization has been refused for those credentials. If the 401 response contains the
same challenge as the prior response, and the user agent has already attempted
authentication at least once, then the user SHOULD be presented the entity that was
given in the response, since that entity might include relevant diagnostic information.

403 (Forbidden)

A 403 error response indicates that the client’s request is formed correctly, but the REST
API refuses to honor it i.e. the user does not have the necessary permissions for the
resource. A 403 response is not a case of insufficient client credentials; that would be
401 (“Unauthorized”).

Authentication will not help and the request SHOULD NOT be repeated. Unlike a 401
Unauthorized response, authenticating will make no difference.

404 (Not Found)

The 404 error status code indicates that the REST API can’t map the client’s URI to a
resource but may be available in the future. Subsequent requests by the client are
permissible.

No indication is given of whether the condition is temporary or permanent. The 410


(Gone) status code SHOULD be used if the server knows, through some internally
configurable mechanism, that an old resource is permanently unavailable and has no
forwarding address. This status code is commonly used when the server does not wish
to reveal exactly why the request has been refused, or when no other response is
applicable.
405 (Method Not Allowed)

The API responds with a 405 error to indicate that the client tried to use an HTTP
method that the resource does not allow. For instance, a read-only resource could
support only GET and HEAD, while a controller resource might allow GET and POST, but
not PUT or DELETE.

A 405 response must include the Allow header, which lists the HTTP methods that the
resource supports. For example:

Allow: GET, POST

406 (Not Acceptable)

The 406 error response indicates that the API is not able to generate any of the client’s
preferred media types, as indicated by the Accept request header. For example, a client
request for data formatted as application/xml will receive a 406 response if the API is
only willing to format data as application/json.
If the response could be unacceptable, a user agent SHOULD temporarily stop receipt of
more data and query the user for a decision on further actions.

412 (Precondition Failed)

The 412 error response indicates that the client specified one or more preconditions in
its request headers, effectively telling the REST API to carry out its request only if certain
conditions were met. A 412 response indicates that those conditions were not met, so
instead of carrying out the request, the API sends this status code.

415 (Unsupported Media Type)

The 415 error response indicates that the API is not able to process the client’s supplied
media type, as indicated by the Content-Type request header. For example, a client
request including data formatted as application/xml will receive a 415 response if the
API is only willing to process data formatted as application/json.
For example, the client uploads an image as image/svg+xml, but the server requires that
images use a different format.
500 (Internal Server Error)

500 is the generic REST API error response. Most web frameworks automatically
respond with this response status code whenever they execute some request handler
code that raises an exception.

A 500 error is never the client’s fault and therefore it is reasonable for the client to retry
the exact same request that triggered this response, and hope to get a different
response.

API response is the generic error message, given when an unexpected condition was
encountered and no more specific message is suitable.

501 (Not Implemented)

The server either does not recognize the request method, or it lacks the ability to fulfill
the request. Usually, this implies future availability (e.g., a new feature of a web-service
API).

Difference between Session and Caching

What is Caching?

Caching is a technique where we can store frequently used data, and web pages are
stored temporarily on the local hard disk for later retrieval. Each request will use the
same cache for different users. One of the more common items stored in a cache in a
Web application environment is commonly displayed database values ; by caching such
information, rather than relying on repeated database calls, the demand on the Web
server and database server's system resources are decreased and the Web application's
scalability increased.

What is session?

Session is a period of time that is shared between the web application and the user. It
refers to a limited time of communication between two systems. Some sessions involve
a client and server, while other sessions involve two personal computers. Each user that
is using the web application has their own session . Session variables will use different
session variables for each different user. Since session variables are stored on the Web
server's memory, storing large objects in a user's session on a site with many
simultaneous users can lead to reduced memory on the Web server

Differences:

 Session data is stored at the user level but caching data is stored at the
application level and shared by all the users.

 Sessions may not improve performance whereas Cache will improve site
performance.

 Items in cache can expire after given time to cache while items in session will stay
till session expires.

 Sessions may change from user to user whereas a single Cache will be maintained
for the entire application.

 Cache wont maintain any state, whereas Sessions will maintain separate state for
every user.

What’s The Difference between Cache and Cookies


Cache and cookies are two different forms of temporary storage kept on client’s machine
to improve the users experience and performance of web pages. Although both of them
stores data on client’s machine but they serve different purposes. Before we go and clear
out the difference between Cache and Cookies, first let’s have a look what are ‘Caches’
and ‘Cookies’.

What are Cookies?

Cookies are small files that contain information useful to a web site — such as password,
preferences, browser, IP Address, date and time of visit, etc. Every time the user loads
the website, the browser sends the cookie back to the server to notify the website of the
user’s previous activity.

Cookies have a certain life span defined by their creators and it expires after the fixed
time span.
Cookies often track information like how frequently the user visits, what are the times of
visits, what banners have been clicked on, what button clicked, user preferences, items
in shopping cart, etc. This allows the site to present you with information customized to
fit your needs.

Cookies are usually used to store information needed for shorter periods. Cookies was
first introduced by Netscape. In those earlier stages cookies did not receive good
acceptance, since rumors said it might hack your personal data. Later people realized
that cookies are actually harmless, and now they are highly accepted.

What are Caches?

A web cache (or HTTP cache) is an information technology for the temporary storage
(caching) of web documents, such as HTML pages and images, to reduce bandwidth
usage, server load, and perceived lag. Cache is just a collection of data downloaded to
help display a web page.

A web cache system stores copies of documents passing through it; subsequent requests
may be satisfied from the cache if certain conditions are met. A web cache system can
refer either to an appliance, or to a software.

For example, when you open websites with large pictures and video’s, it might take
some time to load the website. The web browser stores the site contents like the images,
videos, audio etc. on your computer. So the next time you load the same website you
will find it loading faster.

What’s The Difference Between Cache And Cookies

Although cookies and cache are two ways to store data on client’s machine, but there
are difference between cache and cookies and they serve different purposes.
• Cookie is used to store information to track different characteristics related to user,
while cache is used to make the loading of web pages faster.
• Cookies stores information such as user preferences, while cache will keep resource
files such as audio, video or flash files.
• Typically, cookies expire after some time, but cache is kept in the client’s machine until
they are removed manually by the user.
Definition of Authentication

Authentication mechanism determines the user’s identity before revealing the sensitive


information. It is very crucial for the system or interfaces where the user’s priority is to
protect the confidential information. In the process, the user makes a provable claim
about individual identity (his or her) or an entity’s identity.

The credentials or claim could be a username, password, fingerprint etc. The


authentication and non-repudiation, kind of issues are handled in the application layer.
The inefficient authentication mechanism could significantly affect the availability of the
service.

Example :

For example, there is a sender A sending an electronic document to the receiver B over
the internet. How does the system will identify that the sender A has sent a message
dedicated to the receiver B. An intruder C may intercept, modify and replay the
document in order trick or steal the information this type of attack is called fabrication.

In the given situation authentication mechanism ensures two things; first, it ensures that
the sender and receiver are righteous people and it’s known as data-origin
authentication. Secondly, it ensures the security of the established connection between
sender and receiver with the help of secret session key so that it could not be inferred
and it is known as peer entity authentication.

Definition of Authorization

Authorization technique is used to determine the permissions that are granted to an


authenticated user. In simple words, it checks whether the user is permitted to access
the particular resources or not. Authorization occurs after authentication, where the
user’s identity is assured prior then the access list for the user is determined by looking
up the entries stored in the tables and databases.

Example :

For example, a user X wants to access a particular file from the server. The user will send
a request to the server. The server will verify the user identity. Then, it finds the
corresponding privileges the authenticated user have or whether he/she is allowed to
access that particular file or not. In the following case, the access rights could include
viewing, modifying or deleting the file if the user has authority to perform the following
operations.

You might also like