RESTful Web Services Tutorial


What is REST?

REST in official words, REST is an architectural style built on certain principles using the current “Web” fundamentals. There are 5 basic fundamentals of web which are leveraged to create REST services. Principle 1: Everything Read more…


Best Practices for RESTful Web Services Development

First part My main goal is to focus attention on the reason for the name “representational state transfer”. I think that the most of misundertandings about the REST goes under the adjective “representational”. Most people Read more…

 


What exactly is RESTful programming?

REST is the underlying architectural principle of the web. The amazing thing about the web is the fact that clients (browsers) and servers can interact in complex ways without the client knowing anything beforehand about the Read more…


Best way to return error messages on REST services?

The correct REST approach for errors is to use the HTTP status codes. There is a bewildering array of them (as you can see here) and you might be surprised to see how many may Read more…


HTTP Methods for RESTful Web Services

Correct Representation of a RESTful Architecture: /api/users when called with GET, lists users /api/users when called with POST, creates user record /api/users/1 when called with GET, shows user record when called with PUT, updates user Read more…


PUT vs. POST in REST

You can find assertions on the web that say POST should be used to create a resource, and PUT should be used to modify one PUT should be used to create a resource, and POST should be used to modify one Read more…


What does RESTful Authentication mean and how does it work?

How to handle authentication in a RESTful Client-Server architecture is a matter of debate. Commonly, it can be achieved, in the SOA over HTTP world via: HTTP basic auth over HTTPS; Cookies and session management; Read more…


Form-based authentication for websites

PART I: How To Log In We’ll assume you already know how to build a login+password HTML form which POSTs the values to a script on the server side for authentication. The sections below will Read more…


How I Explained REST to My Wife

Wife: Who is Roy Fielding? Ryan: Some guy. He’s smart. Wife: Oh? What did he do? Ryan: He helped write the first web servers and then did a ton of research explaining why the web Read more…


Best practices for API versioning?

This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API. Since Read more…


Best Practices for securing a REST API / web service

There is a great checklist found on Github: Authentication Don’t reinvent the wheel in Authentication, token generation, password storage. Use the standards. Use Max Retry and jail features in Login. Use encryption on all sensitive data. JWT (JSON Read more…


SOAP vs REST

REST(REpresentational State Transfer) REST is an architectural style. It doesn’t define so many standards like SOAP. REST is for exposing Public APIs(i.e. Facebook API, Google Maps API) over the internet to handle CRUD operations on data. REST Read more…


REST and SOAP fundamentals

The decision between the two will be your first choice in designing a web service, so it is important to understand the pros and cons of the two. It is also important, in the sometimes Read more…


Advantages of REST and SOAP. Where to use REST or SOAP?

Advantages of REST Since REST uses standard HTTP, it is much simpler in just about every way. Creating clients, developing APIs, the documentation is much easier to understand, and there aren’t very many things that Read more…


Differences between SOAP and RESTful web services

Difference between Rest and Soap SOAP SOAP is a protocol. SOAP stands for Simple Object Access Protocol. SOAP can’t use REST because it is a protocol. SOAP uses services interfaces to expose the business logic. Read more…


What is the difference between stateful and stateless?

SOAP vs REST One of the major benefits of SOAP is that you have a WSDL service description. You can pretty much discover the service automatically and generate a useable client proxy from that service Read more…


 

HTTP status codes - Server error responses


500 Internal Server Error
The server has encountered a situation it doesn’t know how to handle.
501 Not Implemented
The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.
502 Bad Gateway
This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
503 Service Unavailable
The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
504 Gateway Timeout
This error response is given when the server is acting as a gateway and cannot get a response in time.
505 HTTP Version Not Supported
The HTTP version used in the request is not supported by the server.
506 Variant Also Negotiates
The server has an internal configuration error: transparent content negotiation for the request results in a circular reference.
507 Insufficient Storage
The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
508 Loop Detected (WebDAV)
The server detected an infinite loop while processing the request.
510 Not Extended
Further extensions to the request are required for the server to fulfill it.
511 Network Authentication Required
The 511 status code indicates that the client needs to authenticate to gain network access.


 

HTTP status codes - Client error responses

400 Bad Request

This response means that server could not understand the request due to invalid syntax.
401 Unauthorized
Although the HTTP standard specifies “unauthorized”, semantically this response means “unauthenticated”. That is, the client must authenticate itself to get the requested response.
402 Payment Required
This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently.
403 Forbidden
The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client’s identity is known to the server.
404 Not Found
The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web.
405 Method Not Allowed
The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.
406 Not Acceptable
This response is sent when the web server, after performing server-driven content negotiation, doesn’t find any content following the criteria given by the user agent.
407 Proxy Authentication Required
This is similar to 401 but authentication is needed to be done by a proxy.
408 Request Timeout
This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.
409 Conflict
This response is sent when a request conflicts with the current state of the server.
410 Gone
This response would be sent when the requested content has been permenantly deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for “limited-time, promotional services”. APIs should not feel compelled to indicate resources that have been deleted with this status code.
411 Length Required
Server rejected the request because the Content-Length header field is not defined and the server requires it.
412 Precondition Failed
The client has indicated preconditions in its headers which the server does not meet.
413 Payload Too Large
Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field.
414 URI Too Long
The URI requested by the client is longer than the server is willing to interpret.
415 Unsupported Media Type
The media format of the requested data is not supported by the server, so the server is rejecting the request.
416 Requested Range Not Satisfiable
The range specified by the Range header field in the request can’t be fulfilled; it’s possible that the range is outside the size of the target URI’s data.
417 Expectation Failed
This response code means the expectation indicated by the Expect request header field can’t be met by the server.
418 I'm a teapot
The server refuses the attempt to brew coffee with a teapot.
421 Misdirected Request
The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
422 Unprocessable Entity (WebDAV)
The request was well-formed but was unable to be followed due to semantic errors.
423 Locked (WebDAV)
The resource that is being accessed is locked.
424 Failed Dependency (WebDAV)
The request failed due to failure of a previous request.
426 Upgrade Required
The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an Upgrade header in a 426 response to indicate the required protocol(s).
428 Precondition Required
The origin server requires the request to be conditional. Intended to prevent the ‘lost update’ problem, where a client GETs a resource’s state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
429 Too Many Requests
The user has sent too many requests in a given amount of time (“rate limiting”).
431 Request Header Fields Too Large
The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.
451 Unavailable For Legal Reasons
The user requests an illegal resource, such as a web page censored by a government.


 

HTTP status codes - Redirection messages

300 Multiple Choice
The request has more than one possible response. The user-agent or user should choose one of them. There is no standardized way of choosing one of the responses.
301 Moved Permanently
This response code means that the URI of the requested resource has been changed. Probably, the new URI would be given in the response.
302 Found
This response code means that the URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
303 See Other
The server sent this response to direct the client to get the requested resource at another URI with a GET request.
304 Not Modified
This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.
305 Use Proxy
Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.
306 unused
This response code is no longer used, it is just reserved currently. It was used in a previous version of the HTTP 1.1 specification.
307 Temporary Redirect
The server sends this response to direct the client to get the requested resource at another URI with same method that was used in the prior request. This has the same semantics as the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: If a POST was used in the first request, a POST must be used in the second request.
308 Permanent Redirect
This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: If a POST was used in the first request, a POST must be used in the second request.


 

HTTP status codes - Successful responses

200 OK

The request has succeeded. The meaning of a success varies depending on the HTTP method:
GET: The resource has been fetched and is transmitted in the message body.
HEAD: The entity headers are in the message body.
PUT or POST: The resource describing the result of the action is transmitted in the message body.
TRACE: The message body contains the request message as received by the server

201 Created

The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a POST request, or after some PUT requests.

202 Accepted

The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.

203 Non-Authoritative Information

This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response.

204 No Content

There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.

205 Reset Content

This response code is sent after accomplishing request to tell user agent reset document view which sent this request.

206 Partial Content

This response code is used because of range header sent by the client to separate download into multiple streams.


207 Multi-Status (WebDAV)

A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate.

208 Multi-Status (WebDAV)

Used inside a DAV: propstat response element to avoid enumerating the internal members of multiple bindings to the same collection repeatedly.

226 IM Used (HTTP Delta encoding)

The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.



 

HTTP status codes - Information responses

100 Continue
This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.
101 Switching Protocol
This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching to.
102 Processing (WebDAV)
This code indicates that the server has received and is processing the request, but no response is available yet.


 

HTTP status codes or HTTP response status codes

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Status codes are defined by section 10 of RFC 2616.

200 OK The request has succeeded. The meaning of a success varies depending on the HTTP method: GET: The resource has been fetched and is transmitted in the message body. HEAD: The entity headers are Read more…


3xx. HTTP status codes – Redirection messages

300 Multiple Choice The request has more than one possible response. The user-agent or user should choose one of them. There is no standardized way of choosing one of the responses. 301 Moved Permanently This response Read more…


4xx. HTTP status codes – Client error responses

400 Bad Request This response means that server could not understand the request due to invalid syntax. 401 Unauthorized Although the HTTP standard specifies “unauthorized”, semantically this response means “unauthenticated”. That is, the client must Read more…


5xx. HTTP status codes – Server error responses

500 Internal Server Error The server has encountered a situation it doesn’t know how to handle. 501 Not Implemented The request method is not supported by the server and cannot be handled. The only methods Read more…



 

HTTP methods or HTTP verbs

HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred as HTTP verbs. Each of them implements a different semantic, but some common features are shared by a group of them: e.g. a request method can be safe, idempotent, or cacheable.


GET

The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

HEAD

The HEAD method asks for a response identical to that of a GET request, but without the response body.

POST

The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server

PUT

The PUT method replaces all current representations of the target resource with the request payload.


DELETE

The DELETE method deletes the specified resource.

CONNECT

The CONNECT method establishes a tunnel to the server identified by the target resource.

OPTIONS

The OPTIONS method is used to describe the communication options for the target resource.

TRACE

The TRACE method performs a message loop-back test along the path to the target resource.

PATCH

The PATCH method is used to apply partial modifications to a resource.


Brief explanation of commonly used HTTP verbs.

GET:

Request has bodyNo
Successful response has bodyYes
SafeYes
IdempotentYes
CacheableYes
Allowed in HTML formsYes

Syntax

GET http://www.example.com/customers/12345GET http://www.example.com/customers/12345/ordersGET http://www.example.com/buckets/sample

HEAD:

Request has bodyNo
Successful response has bodyNo
SafeYes
IdempotentYes
CacheableYes
Allowed in HTML formsNo

Syntax

HEAD http://www.example.com/customers/12345HEAD http://www.example.com/customers/12345/ordersHEAD http://www.example.com/buckets/sample

POST:


Request has bodyYes
Successful response has bodyYes
SafeNo
IdempotentNo
CacheableOnly if freshness information is included
Allowed in HTML formsYes

Syntax

POST http://www.example.com/customersPOST http://www.example.com/customers/12345/orders

PUT:

Request has bodyYes
Successful response has bodyNo
SafeNo
IdempotentYes
CacheableNo
Allowed in HTML formsNo

Syntax

PUT http://www.example.com/customers/12345PUT http://www.example.com/customers/12345/orders/98765PUT http://www.example.com/buckets/secret_stuff

DELETE:

Request has bodyMay
Successful response has bodyMay
SafeNo
IdempotentYes
CacheableNo
Allowed in HTML formsNo

Syntax

DELETE http://www.example.com/customers/12345DELETE http://www.example.com/customers/12345/ordersDELETE http://www.example.com/bucket/sample

CONNECT:

Request has bodyNo
Successful response has bodyYes
SafeNo
IdempotentNo
CacheableNo
Allowed in HTML formsNo

Syntax

CONNECT www.example.com:443 HTTP/1.1

OPTIONS:

Request has bodyNo
Successful response has bodyYes
SafeYes
IdempotentYes
CacheableNo
Allowed in HTML formsNo

Syntax

OPTIONS /index.html HTTP/1.1OPTIONS * HTTP/1.1

TRACE:

Request has bodyNo
Successful response has bodyNo
SafeNo
IdempotentYes
CacheableNo
Allowed in HTML formsNo

Syntax

TRACE /index.html

PATCH

Request has bodyYes
Successful response has bodyNo
SafeNo
IdempotentNo
CacheableNo
Allowed in HTML formsNo

Syntax

PATCH /file.txt HTTP/1.1 


HTTP headers - HTTP Tutorial

HTTP headers allow the client and the server to pass additional information with the request or the response. A request header consists of its case-insensitive name followed by a colon ‘:‘, then by its value (without line breaks). Leading white space before the value is ignored.

Headers can be grouped according to their contexts:

1. General header: Headers applying to both requests and responses but with no relation to the data eventually transmitted in the body.

2. Request header: Headers containing more information about the resource to be fetched or about the client itself.

3. Response header: Headers with additional information about the response, like its location or about the server itself (name and version etc.).

4. Entity header: Headers containing more information about the body of the entity, like its content length or its MIME-type.

Request Header fields:

Providing some common request header fields:

Header field nameDescriptionExampleStatus
User-AgentThe user agent string of the user agent.User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0Permanent
AcceptMedia type(s) that is(/are) acceptable for the response.Accept: text/plainPermanent
Accept-CharsetCharacter sets that are acceptable.Accept-Charset: utf-8Permanent
Accept-EncodingList of acceptable encodings.Accept-Encoding: gzip, deflatePermanent
Accept-LanguageList of acceptable human languages for response.Accept-Language: en-USPermanent
AuthorizationAuthentication credentials for HTTP authentication.Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==Permanent
Cache-ControlUsed to specify directives that must be obeyed by all caching mechanisms along the request-response chain.Cache-Control: no-cachePermanent
ConnectionControl options for the current connection and list of hop-by-hop request fields. Must not be used with HTTP/2.Connection: keep-aliveConnection: UpgradePermanent
Content-LengthThe length of the request body in octets (8-bit bytes).Content-Length: 348Permanent
Content-TypeThe Media type of the body of the request (used with POST and PUT requests).Content-Type: application/x-www-form-urlencodedPermanent

 

Response Header fields:

Field nameDescriptionExampleStatus
Access-Control-Allow-Origin,

Access-Control-Allow-Credentials,


Access-Control-Expose-Headers,


Access-Control-Max-Age,


Access-Control-Allow-Methods,


Access-Control-Allow-Headers

Specifying which web sites can participate in cross-origin resource sharingAccess-Control-Allow-Origin: *Permanent: standard
ExpiresGives the date/time after which the response is considered stale (in “HTTP-date” format as defined by RFC 7231)Expires: Thu, 01 Dec 1994 16:00:00 GMTPermanent: standard
An HTTP cookieSet-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1Permanent: standard
Strict-Transport-SecurityA HSTS Policy informing the HTTP client how long to cache the HTTPS only policy and whether this applies to subdomains.Strict-Transport-Security: max-age=16070400; includeSubDomainsPermanent: standard
Accept-PatchSpecifies which patch document formats this server supportsAccept-Patch: text/example;charset=utf-8Permanent
Accept-RangesWhat partial content range types this server supports via byte servingAccept-Ranges: bytesPermanent
AgeThe age the object has been in a proxy cache in secondsAge: 12Permanent
AllowValid methods for a specified resource. To be used for a 405 Method not allowedAllow: GET, HEADPermanent
Alt-SvcA server uses “Alt-Svc” header (meaning Alternative Services) to indicate that its resources can also be accessed at a different network location (host or port) or using a different protocolWhen using HTTP/2, servers should instead send an ALTSVC frame.Alt-Svc: http/1.1="http2.example.com:8001"; ma=7200Permanent
Cache-ControlTells all caching mechanisms from server to client whether they may cache this object. It is measured in secondsCache-Control: max-age=3600Permanent
ConnectionControl options for the current connection and list of hop-by-hop response fields.Must not be used with HTTP/2.Connection: closePermanent
Content-DispositionAn opportunity to raise a “File Download” dialogue box for a known MIME type with binary format or suggest a filename for dynamic content. Quotes are necessary with special characters.Content-Disposition: attachment; filename="fname.ext"Permanent
Content-EncodingThe type of encoding used on the data. See HTTP compression.Content-Encoding: gzipPermanent
Content-LanguageThe natural language or languages of the intended audience for the enclosed contentContent-Language: daPermanent
Content-LengthThe length of the response body in octets (8-bit bytes)Content-Length: 348Permanent
Content-LocationAn alternate location for the returned dataContent-Location: /index.htmPermanent
Content-RangeWhere in a full body message this partial message belongsContent-Range: bytes 21010-47021/47022Permanent
Content-TypeThe MIME type of this contentContent-Type: text/html; charset=utf-8Permanent
DateThe date and time that the message was sent (in “HTTP-date” format as defined by RFC 7231)Date: Tue, 15 Nov 1994 08:12:31 GMTPermanent
ETagAn identifier for a specific version of a resource, often a message digestETag: "737060cd8c284d8af7ad3082f209582d"Permanent
Last-ModifiedThe last modified date for the requested object (in “HTTP-date” format as defined by RFC 7231)Last-Modified: Tue, 15 Nov 1994 12:45:26 GMTPermanent

What can be controlled by HTTP



This extensible nature of HTTP has, over time, allowed for more control and functionality of the Web. Cache or authentication methods were functions handled early in HTTP history. The ability to relax the origin constraint, by contrast, has only been added in the 2010s.

Here is a list of common features controllable with HTTP.

Cache
How documents are cached can be controlled by HTTP. The server can instruct proxies, and clients, what to cache and for how long. The client can instruct intermediate cache proxies to ignore the stored document.

Relaxing the origin constraint
To prevent snooping and other privacy invasions, Web browsers enforce strict separation between Web sites. Only pages from the same origin can access all the information of a Web page. Though such constraint is a burden to the server, HTTP headers can relax this strict separation server-side, allowing a document to become a patchwork of information sourced from different domains (there could even be security-related reasons to do so).

Authentication
Some pages may be protected so only specific users can access it. Basic authentication may be provided by HTTP, either using the WWW-Authenticate and similar headers, or by setting a specific session using HTTP cookies.

Proxy and tunneling
Servers and/or clients are often located on intranets and hide their true IP address to others. HTTP requests then go through proxies to cross this network barrier. Not all proxies are HTTP proxies. The SOCKS protocol, for example, operates at a lower level. Others, like ftp, can be handled by these proxies.

Sessions
Using HTTP cookies allows you to link requests with the state of the server. This creates sessions, despite basic HTTP being a state-less protocol. This is useful not only for e-commerce shopping baskets, but also for any site allowing user configuration of the output.

Basic Features of HTTP - HTTP Protocol



HTTP is simple

Even with more complexity, introduced in HTTP/2 by encapsulating HTTP messages into frames, HTTP is generally designed to be simple and human readable. HTTP messages can be read and understood by humans, providing easier developer testing, and reduced complexity for new-comers.

HTTP is extensible

Introduced in HTTP/1.0, HTTP headers made this protocol easy to extend and experiment with. New functionality can even be introduced by a simple agreement between a client and a server about a new header’s semantics.

HTTP is connectionless:

It is a connectionless approach in which HTTP client i.e., a browser initiates the HTTP request and after the request is sends the client disconnects from server and waits for the response.

HTTP is stateless, but not sessionless

HTTP is stateless: there is no link between two requests being successively carried out on the same connection. This immediately has the prospect of being problematic for users attempting to interact with certain pages coherently, for example, using e-commerce shopping baskets. But while the core of HTTP itself is stateless, HTTP cookies allow the use of stateful sessions. Using header extensibility, HTTP Cookies are added to the workflow, allowing session creation on each HTTP request to share the same context, or the same state.

HTTP is media independent:

It refers to any type of media content can be sent by HTTP as long as both the server and the client can handle the data content.



Hierarchy of HTTP and Communication -HTTP Tutorial

Hierarchy of HTTP

HTTP has the following four hierarchies.

hierarchyOverview
Application layerDetermine the movement of communication to be used in the application. TCP / IP is also included in this
Transport layerProvide data flow between computers connected by the network. There are TCP and UDP.
Network layerThe layer responsible for moving packets on the network. The path of the network is also decided by this layer.
Link layerA layer that carries configuration information related to hardware. Connections with device drivers and cable connections.

Communication order

When actually communicating, information is handled in the following form.

When sending:

  1. Specify the web page requested by the application layer with an HTTP request.
  2. We divide the HTTP requests coming from the application layer finely in the transport layer and give serial numbers and port numbers.
  3. Add the destination MAC address in the network layer.
  4. An HTTP request is sent from the link layer.

On reception:

  1. Receive HTTP request from link layer.
  2. Remove the MAC address information at the network layer.
  3. Assemble HTTP requests finely divided at the transport layer based on serial numbers and port numbers.
  4. Get information on the web page specified in the application layer.


 

How HTTP works? - HTTP Tutorial

When the client wants to communicate with a server, either being the final server or an intermediate proxy, it performs the following steps:Client server chain

1. Open a TCP connection: The TCP connection will be used to send a request, or several, and receive an answer. The client may open a new connection, reuse an existing connection, or open several TCP connections to the servers.

2. Send an HTTP message: HTTP messages (before HTTP/2) are human-readable. With HTTP/2, these simple messages are encapsulated in frames, making them impossible to read directly, but the principle remains the same.

GET / HTTP/1.1Host: youtube.comAccept-Language: en

3. Read the response sent by the server:

HTTP/1.1 200 OKDate: Sat, 09 Oct 2010 14:28:02 GMTServer: ApacheLast-Modified: Tue, 01 Dec 2009 20:18:22 GMTETag: "51142bc1-7449-479b075b2891b"Accept-Ranges: bytesContent-Length: 29769Content-Type: text/html<!DOCTYPE html... (here comes the 29769 bytes of the requested web page)

4. Close or reuse the connection for further requests.


If HTTP pipelining is activated, several requests can be sent without waiting for the first response to be fully received. HTTP pipelining has proven difficult to implement in existing networks, where old pieces of software coexist with modern versions. HTTP pipelining has been superseded in HTTP/2 with more robust multiplexing requests within a frame.



 

What is HTTP? - HTTP Tutorial

HTTP is a protocol which allows the fetching of resources, such as HTML documents. It is the foundation of any data exchange on the Web and a client-server protocol, which means requests are initiated by the recipient, usually the Web browser. A complete document is reconstructed from the different sub-documents fetched, for instance, text, layout description, images, videos, scripts, and more.

A Web document is the composition of different resources


Clients and servers communicate by exchanging individual messages (as opposed to a stream of data). The messages sent by the client, usually a Web browser, are called requests and the messages sent by the server as an answer are called responses.

HTTP as an application layer protocol, on top of TCP (transport layer) and IP (network layer) and below the presentation layer.Designed in the early 1990s, HTTP is an extensible protocol which has evolved over time. It is an application layer protocol that is sent over TCP, or over a TLS-encrypted TCP connection, though any reliable transport protocol could theoretically be used.

Due to its extensibility, it is used to not only fetch hypertext documents, but also images and videos or to post content to servers, like with HTML form results. HTTP can also be used to fetch parts of documents to update Web pages on demand.



What is the best way to learn JavaScript?



You do not know that you do not know

The reason for this is that almost every web developer came across about the need to handle JavaScript . As the most common approach to remembering JavaScript without understanding , search the sample code on the fly and copipe. The problem with ‘learning’ in this hand is that developers do not actually learn that language, and additionally they misunderstand that they know it. The fact that I learned while working with JavaScript for years has me learned that I do not know for the first time I really understand it. This is a kind of circulating story, what you really need is a person who tells us that you do not understand, it is real learning. Although I’ve only done simple onClick handlers and form validation merely linking sample code, I have interviewed too many with prosely someone who lists JavaScript in my resume. It is a good idea to use a framework like jQuery or Dojo , but without properly understanding the JavaScript behind them you will not master those toolkits. Below is the idea that I think as basic knowledge, intermediate level, advanced level knowledge to express many elements of JavaScript .


Basic level of JavaScript understanding

  • Know basic programming tools, such as loops, if statements, try / catch etc.
  • Know that there are various methods for function definition and application. The same applies to anonymous functions .
  • Understand the basic scope definition principle, global scope ( object ) versus object scope (closure).
  • Understand the role of context and how to use this variable .
  • Understand the various ways of instantiating and declaring objects . The same is true that the function is an object .
  • Understand what is false with JavaScript comparison operators such as ‘<‘, ‘>’, ‘==’, ‘===’ and how objects and strings are compared. Cast as well.
  • How Array indexes attributes and functions of objects and how it differs from real arrays. ( Object literals vs. array literals).

Intermediate level of JavaScript understanding

  • Understand how the timer works, that is, when and how it will be available. The same applies to asynchronous method calls.
  • Know the callback and function application deeply. For example, you can manipulate the context with the ‘call’ and ‘apply’ methods and pass the function as an argument (function argument passing).
  • Understand JSON notation and eval function .
  • Understand how closures affect code performance and how they are used to create private variables .
  • Familiar with calling (lovely), (function () {}) ().
  • AJAX and the object of the serialization

Advanced level of understanding of JavaScript

In this paragraph, I do not think much of the specific situation, so there are some doubtful parts so JS advanced users should refer to the original text.

  • Understand the arguments variable of the method , how can it be used , overload the functionwith arguments.length, and recursive call with arguments.callee ? Let’s add that the use of arguments.callee is dangerous, as can be seen from ECMAScript 5 ‘s Strict mode not supported * 1 . Even if both jQuery (up to version 1.4) and Dojo are using it.
  • How to use higher closures like self-memoization, currying, partial application of functions
  • Functions and html proto -typing , i.e. prototype chain and basic JavaScript objects and functions (eg: Array) the use to reduce the code that.
  • How to use Object type, instanceof and typeof
  • Regular Expression and Regular Expression Compilation
  • With statement and why should not you use it
  • The most difficult thing is to combine all of these tools into a clean, clean, robust, fast and maintainable cross-browser compliant code.

The last point of the advanced level is particularly important and hardest to reach. Given the inadvertent nature of JavaScript , it easily goes into a vicious circle of spaghetti code that can not maintain your application . Once you learn the JavaScript language itself you can truly master it by organizing it and binding it to each other in the context of large applications. It requires a couple of years of training and failure, and one book can not be acquired. I am using JavaScript on a daily basis for several hours every day for several years and I am continuing to find a better way to write my own code.

For these reasons, it is dangerous to jump a step further to some framework, and jQuery code tends to be unmanageable. Dojo encourages this by its own class and package system.

Since JavaScript is now penetrating to the back end by Node.js etc., we decided to separate the above listed requirements from the web-specific knowledge. The aspect of the web (ie DOM and IE) gave JavaScript a bad name , trembling all programmers and making it jerky. If you try to use JavaScript in the context of the web, there are additional items that all good developers should know.

  • Effectively manipulating DOM and it. That is, adding, deleting, changing nodes. The same applies to text nodes.
  • Including using a tool such as Document fragment to minimize browser re-flow.
  • Extract information from the DOM in a way that is compatible with cross-browser (eg style, position etc.). Such things are done very well with frameworks such as jQuery and Dojo, but understand the difference between extracting information as represented by CSS versus style tag and specifying position and size It is important.
  • How to achieve event handling, binding , unbinding , bubbling, ie the desired callback context with cross browser support . Again, this is handled very well if it is via the framework, but individuals should also understand the difference between IE and the W3Cstandard browser .
  • Expando vs. attribute setting and their performance are different, there is a mismatch (naming discrepancies) with the name.
  • Regular expression to extract DOM node
  • Effectively detect browser functions and graceful degradation of them (graceful degradation).

If you do not copy and find that you are developing the function you want, you can assert that you know JavaScript . Until then do not advertise that you know JavaScript and so on .Until then do not advertise that you know JavaScript and so on .

If you have aspects of JavaScript I missed, please let me know from comments. Also, please share the experiences I’ve met with people who claim to know JS and other languages.

In addition, I am not a front-end developer, but a back-end developer and I have evolved to a full stack developer. Today, almost all backend developers need to learn JavaScript , which is what the article is intended to do. There is no intention to look down, not to say that everything in JS is known. My hope is that more people are aware that JavaScript is a vast and powerful language, more than it looks.



 

JSON examples for DEVELOPERS

Here I’ll show you different ways in how JSON is used in real-life scenarios. Whether you need to access third-party data or provide a means for exchanging data between different systems, you’ll find that JSON fits perfectly in all these situations.


1. YouTube API JSON Response (partial results):

{  "kind": "youtube#searchListResponse",  "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/PaiEDiVxOyCWelLPuuwa9LKz3Gk\"",  "nextPageToken": "CAUQAA",  "regionCode": "KE",  "pageInfo": {    "totalResults": 4249,    "resultsPerPage": 5  },  "items": [    {      "kind": "youtube#searchResult",      "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/QpOIr3QKlV5EUlzfFcVvDiJT0hw\"",      "id": {        "kind": "youtube#channel",        "channelId": "UCJowOS1R0FnhipXVqEnYU1A"      }    },    {      "kind": "youtube#searchResult",      "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/AWutzVOt_5p1iLVifyBdfoSTf9E\"",      "id": {        "kind": "youtube#video",        "videoId": "Eqa2nAAhHN0"      }    },    {      "kind": "youtube#searchResult",      "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/2dIR9BTfr7QphpBuY3hPU-h5u-4\"",      "id": {        "kind": "youtube#video",        "videoId": "IirngItQuVs"      }    }  ]}

2. Twitter API JSON Response

[{  "created_at": "Thu Jun 22 21:00:00 +0000 2017",  "id": 877994604561387500,  "id_str": "877994604561387520",  "text": "Creating a Grocery List Manager Using Angular, Part 1: Add &amp; Display Items https://t.co/xFox78juL1 #Angular",  "truncated": false,  "entities": {    "hashtags": [{      "text": "Angular",      "indices": [103, 111]    }],    "symbols": [],    "user_mentions": [],    "urls": [{      "url": "https://t.co/xFox78juL1",      "expanded_url": "http://buff.ly/2sr60pf",      "display_url": "buff.ly/2sr60pf",      "indices": [79, 102]    }]  },  "source": "<a href=\"http://bufferapp.com\" rel=\"nofollow\">Buffer</a>",  "user": {    "id": 772682964,    "id_str": "772682964",    "name": "SitePoint JavaScript",    "screen_name": "SitePointJS",    "location": "Melbourne, Australia",    "description": "Keep up with JavaScript tutorials, tips, tricks and articles at SitePoint.",    "url": "http://t.co/cCH13gqeUK",    "entities": {      "url": {        "urls": [{          "url": "http://t.co/cCH13gqeUK",          "expanded_url": "http://sitepoint.com/javascript",          "display_url": "sitepoint.com/javascript",          "indices": [0, 22]        }]      },      "description": {        "urls": []      }    },    "protected": false,    "followers_count": 2145,    "friends_count": 18,    "listed_count": 328,    "created_at": "Wed Aug 22 02:06:33 +0000 2012",    "favourites_count": 57,    "utc_offset": 43200,    "time_zone": "Wellington",  },}]

3. Local REST JSON File

{  "total": 25,  "limit": 10,  "skip": 0,  "data": [{    "_id": "5968fcad629fa84ab65a5247",    "first_name": "Sabrina",    "last_name": "Mayert",    "address": "69756 Wendy Junction",    "phone": "1-406-866-3476 x478",    "email": "donny54@yahoo.com",    "updatedAt": "2017-07-14T17:17:33.010Z",    "createdAt": "2017-07-14T17:17:33.010Z",    "__v": 0  }, {    "_id": "5968fcad629fa84ab65a5246",    "first_name": "Taryn",    "last_name": "Dietrich",    "address": "42080 Federico Greens",    "phone": "(197) 679-7020 x98462",    "email": "betty_schaefer1@gmail.com",    "updatedAt": "2017-07-14T17:17:33.006Z",    "createdAt": "2017-07-14T17:17:33.006Z",    "__v": 0  },  ...  ]}

4. JSON Server Example

{  "clients": [    {      "id": "59761c23b30d971669fb42ff",      "isActive": true,      "age": 36,      "name": "Dunlap Hubbard",      "gender": "male",      "company": "CEDWARD",      "email": "dunlaphubbard@cedward.com",      "phone": "+1 (890) 543-2508",      "address": "169 Rutledge Street, Konterra, Northern Mariana Islands, 8551"    },    {      "id": "59761c233d8d0f92a6b0570d",      "isActive": true,      "age": 24,      "name": "Kirsten Sellers",      "gender": "female",      "company": "EMERGENT",      "email": "kirstensellers@emergent.com",      "phone": "+1 (831) 564-2190",      "address": "886 Gallatin Place, Fannett, Arkansas, 4656"    },    {      "id": "59761c23fcb6254b1a06dad5",      "isActive": true,      "age": 30,      "name": "Acosta Robbins",      "gender": "male",      "company": "ORGANICA",      "email": "acostarobbins@organica.com",      "phone": "+1 (882) 441-3367",      "address": "697 Linden Boulevard, Sattley, Idaho, 1035"    }  ]}

5. Example Google Maps JSON File

{  "markers": [    {      "name": "Rixos The Palm Dubai",      "position": [25.1212, 55.1535],    },    {      "name": "Shangri-La Hotel",      "location": [25.2084, 55.2719]    },    {      "name": "Grand Hyatt",      "location": [25.2285, 55.3273]    }  ]}

6. Example Colors JSON File

{  "colors": [    {      "color": "black",      "category": "hue",      "type": "primary",      "code": {        "rgba": [255,255,255,1],        "hex": "#000"      }    },    {      "color": "white",      "category": "value",      "code": {        "rgba": [0,0,0,1],        "hex": "#FFF"      }    },    {      "color": "red",      "category": "hue",      "type": "primary",      "code": {        "rgba": [255,0,0,1],        "hex": "#FF0"      }    },    {      "color": "blue",      "category": "hue",      "type": "primary",      "code": {        "rgba": [0,0,255,1],        "hex": "#00F"      }    },    {      "color": "yellow",      "category": "hue",      "type": "primary",      "code": {        "rgba": [255,255,0,1],        "hex": "#FF0"      }    },    {      "color": "green",      "category": "hue",      "type": "secondary",      "code": {        "rgba": [0,255,0,1],        "hex": "#0F0"      }    },  ]}

7. WordPress JSON Example

[  {      "id": 157538,      "date": "2017-07-21T10:30:34",      "date_gmt": "2017-07-21T17:30:34",      "guid": {          "rendered": "https://www.hello.com/?p=157538"      },      "modified": "2017-07-23T21:56:35",      "modified_gmt": "2017-07-24T04:56:35",      "slug": "why-the-iot-threatens-your-wordpress-site-and-how-to-fix-it",      "status": "publish",      "type": "post",      "link": "https://www.hello.com/why-the-iot-threatens-your-wordpress-site-and-how-to-fix-it/",      "title": {          "rendered": "Why the IoT Threatens Your WordPress Site (and How to Fix It)"      },      "content": {         ...      },      "excerpt": {          ...      },      "author": 72546,      "featured_media": 157542,      "comment_status": "open",      "ping_status": "closed",      "sticky": false,      "template": "",      "format": "standard",      "meta": [],      "categories": [          6132      ],      "tags": [          1798,          6298      ],      }  ]

8. GeoIP JSON Example

{  "as": "AS16509 Amazon.com, Inc.",  "city": "Boardman",  "country": "United States",  "countryCode": "US",  "isp": "Amazon",  "lat": 45.8696,  "lon": -119.688,  "org": "Amazon",  "query": "54.148.84.95",  "region": "OR",  "regionName": "Oregon",  "status": "success",  "timezone": "America\/Los_Angeles",  "zip": "97818"}

9. Database JSON File

[{  "_id": {    "$oid": "5968dd23fc13ae04d9000001"  },  "product_name": "sildenafil citrate",  "supplier": "Wisozk Inc",  "quantity": 261,  "unit_cost": "$10.47"}, {  "_id": {    "$oid": "5968dd23fc13ae04d9000002"  },  "product_name": "Mountain Juniperus ashei",  "supplier": "Keebler-Hilpert",  "quantity": 292,  "unit_cost": "$8.74"}, {  "_id": {    "$oid": "5968dd23fc13ae04d9000003"  },  "product_name": "Dextromathorphan HBr",  "supplier": "Schmitt-Weissnat",  "quantity": 211,  "unit_cost": "$20.53"}]

10. Test Data JSON Example

[{  "id": 1,  "first_name": "Jeanette",  "last_name": "Penddreth",  "email": "jpenddreth0@census.gov",  "gender": "Female",  "ip_address": "26.58.193.2"}, {  "id": 2,  "first_name": "Giavani",  "last_name": "Frediani",  "email": "gfrediani1@senate.gov",  "gender": "Male",  "ip_address": "229.179.4.212"}, {  "id": 3,  "first_name": "Noell",  "last_name": "Bea",  "email": "nbea2@imageshack.us",  "gender": "Female",  "ip_address": "180.66.162.255"}, {  "id": 4,  "first_name": "Willard",  "last_name": "Valek",  "email": "wvalek3@vk.com",  "gender": "Male",  "ip_address": "67.76.188.26"}]


Reference: wikipedia: https://en.wikipedia.org/wiki/JSONjson Official:http://json.org/examplesitepoint: https://www.sitepoint.com/10-example-json-files/