Skip to content

Web Application Development

baltasarb edited this page Jul 28, 2018 · 2 revisions

Table of Contents

Hypertext Transfer Protocol

Requests

Resources : Tutorials Point

Structure :

Method Path Version of the Protocol
Headers
Empty Line
Body

Method defines the type of request to be performed on the resource indetified by the URI specified by the path. It can be one of the following :

Path is the URI, it identifies the resource on which the request should be applied.
Headers can be zero or more.
Empty Line signals the end of the headers.
Body is optional.

Back to the top

Methods

Idempotency and Safety

Idempotency is the capacity of a request to be made multiple times while having the same result on the resource. For instance, a get request will return the same response if it is made 1 or 1000 times. On the other side a post will create new resources each time it is made, therefore it is not idempotent.

Safety relates to the resource's ability to remain unchanged after the request is made. A get will (should not in any case) change the resource it requests. A post will create a new resource, changing it's state, therefore it is considered not safe.

Method Idempotent Safe
OPTIONS yes yes
GET yes yes
HEAD yes yes
PUT yes no
POST no no
DELETE yes no
PATCH no no

Get

Description :
Idempotency :
Safety :
Response Codes :

Post

Description :
The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header. The POST method is used to create data on the server. Idempotency :
Safety :
Response Codes :

Differences between PUT and POST :

  • Intent difference:
    The target resource in a POST request is intended to handle the enclosed representation according to the resource's own semantics, whereas the enclosed representation in a PUT request is defined as replacing the state of the target resource.
  • Indempotency :
    Calling PUT once or several times successively has the same effect (that is no side effect), where successive identical POST may have additional effects, like passing an order several times.

Delete

Description :
Idempotency :
Safety :
Response Codes :

Idempotency :

Although delete is considered idempotent there is one caveat. The data deleted will be always removed from the server, but in subsequent calls, the response might be a 404 (Not Found) instead of a 200 (OK) or 204 (No Content) since the resource will no longer be present in the server.

Put

Description :
Idempotency :
Safety :
Response Codes :

  • 200 (OK), 204 (No Content) - If the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation.
  • 201 (Created) - If the target resource does not have a current representation and the PUT successfully creates one.
  • 409 (Conflict) - When a PUT representation is inconsistent with the target resource, the origin server SHOULD either make them consistent, by transforming the representation or changing the resource configuration, or respond with an appropriate error message containing sufficient information to explain why the representation is unsuitable.
  • 415 (Unsupported Media Type) - Specific to constraints on Content-Type values.

When a PUT representation is inconsistent with the target resource, the origin server SHOULD either make them consistent, by transforming the representation or changing the resource configuration, or respond with an appropriate error message containing sufficient information to explain why the representation is unsuitable.
The 409 (Conflict) or 415 (Unsupported Media Type) status codes are suggested, with the latter being specific to constraints on Content-Type values. The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it also MAY have side effects on other resources; i.e., new resources may be created, or existing ones modified, by the application of a PATCH.
Essencialmente um patch diz que instruções devem ser feitas para alterar um determinado recurso, essas instruções podem afectar outros recursos ou criar novos. Desta forma é não idempotente e não safe.

Back to the top

Responses

Resources : Tutorials Point, RFC

HTTP-Version Status-Code Reason-Phrase  
Headers

An empty line (i.e., a line with nothing preceding the CRLF) 
indicating the end of the header fields

Optionally a message-body

Status codes:

  • 1xx: Informational - Request received, continuing process.

  • 2xx: Success - The action was successfully received, understood, and accepted.

  • 3xx: Redirection - Further action must be taken in order to complete the request.

  • 4xx: Client Error - The request contains bad syntax or cannot be fulfilled.

  • 5xx: Server Error - The server failed to fulfill an apparently valid request.

Complete list of status codes :

Code Reason
100 Continue
101 Switching Protocols
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
307 Temporary Redirect
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Time-out
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request-URI Too Large
415 Unsupported Media Type
416 Requested range not satisfiable
417 Expectation Failed
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Time-out
505 HTTP Version not supported

Note: The reason phrases listed here are only recommendations -- they may be replaced by local equivalents without affecting the protocol.

Headers

Link

The Link header in HTTP allows the server to point an interested client to another resource containing metadata about the requested resource. It allows for the metadata to be given without actually touching the resource in question, even if it is a movie or a photograph. Typical uses of the linked metadata file may be to express:

  • A map of different language, content-type and version-specific URIs.
  • Licensing, such as Creative Commons.
  • Information about how to edit the file.
  • Policy information about appropriate use and/or distribution of the data.

Back to the top

Hypermedia APIs

What is hypermedia?

TODO

Advantages and disadvantages of hypermedia

Advantages

  • Responses follow some type of norm called media type.
  • Allows transitioning between resources by following the links provided by each resource, discoverability.
  • The nature of hypermedia allows for dinamic applications, for instance, a link might appear on a response but not in another, the client can act accordingly.
  • More flexibility. New features can be added and made available immediatly to users and certain aspects of the API like changing resources or requiring additional GET parameters can be changed without breaking backwards compatibility (If implemented correctly by the user).
  • Mantains business logic in one place.
  • Increases discoverability of api resources.

Disadvantages

  • Hypermedia is built in a way that requires more requests to get the data. On a poor connection that migh be problematic. It can be considered an advantage aswell if you know exaclty what you are looking for, requiring you to get only the data you need and no more than that.

TODO

Back to the top

HAL

Resources : IETF Draft
Media type : application/hal+json
Strengths :

  • Dynamic and nestable.
  • Easy to read and implement.
  • URL templating.
  • Inclusion of documentation.
  • Supports JSON and XML.

Weaknesses :

  • JSON and XML are architecturaly different.

Reserved properties : [ _links , _embedded , link objects , link object key , link object url , templated , deprecation , name , profile , title , hreflang ]
Mandatory properties :

  • href inside link objects.

HAL document example :

GET /orders HTTP/1.1
   Host: example.org
   Accept: application/hal+json

   HTTP/1.1 200 OK
   Content-Type: application/hal+json

   {
     "_links": {
       "self": { 
           "href": "/orders" //REQUIRED
        },
       "next": { 
           "href": "/orders?page=2" //REQUIRED
        },
       "find": { 
           "href": "/orders{?id}", //REQUIRED
           "templated": true 
        }
     },
     "_embedded": {
       "orders": [{
           "_links": {
                "self": { 
                    "href": "/orders/123" //REQUIRED
                },
                "basket": { 
                    "href": "/baskets/98712" //REQUIRED
                    },
                "customer": {
                    "href": "/customers/7809" //REQUIRED
                }
           },
           "total": 30.00,
           "currency": "USD",
           "status": "shipped",
         },{
           "_links": {
                "self": { 
                    "href": "/orders/124" //REQUIRED
                },
                "basket": { 
                    "href": "/baskets/97213" //REQUIRED
                },
                "customer": { 
                    "href": "/customers/12369" //REQUIRED
                }
           },
           "total": 20.00,
           "currency": "USD",
           "status": "processing"
       }]
     },
     "currentlyProcessing": 14,
     "shippedToday": 20
   }

A resource object like this represents a resource and has two reserved properties, _links and _embedded. All properties are optional except the href property inside a link object like self or next. CurrentlyProcessing and shippedToday reprent the resource object's state. The links tell us the next, self and find URIs. Each of them allows the document user to transverse the application.
The _embedded property "is an object whose property names are link relation types and values are either a Resource Object or an array of Resource Objects wich may be a full, partial, or inconsistent version of the representation served from the target URI".

Back to the top

HAL-FORMS

Resources : The HAL-FORMS Media Type
Media type : application/prs.hal-forms+json
Description : The HAL-FORMS media type is a JSON document that contains information on the HTTP method, message content-type, and parameters to use when making a templated request to a HAL server. This media type can be used to provide dynamic state transition descriptions at runtime.
Properties : [ _links , link object , link object key , link object url , _templates , template object , template key , title , method , contentType , properties , property object , name , prompt , readOnly , regex , required , templated , value ]
Mandatory properties :

  • Link object key and url. In this link object self is the key, and href the url associated to the key :
"self" : {
    "href" : "http://api.example.org/rels/create"
 }
  • Template key and method.
  • Property name in a property.

HAL-FORMS document example :

{
  "_links" : {
     "linkKey" : {//REQUIRED
      "href" : "http://api.example.org/rels/create"//REQUIRED
    }
 },
  "_templates" : {
    "templateKey" : {//REQUIRED
      "title" : "Create",
      "method" : "post",//REQUIRED
      "contentType" : "application/JSON",
      "properties" : [
        {
            "name" : "title", //REQUIRED
            "required" : true, "value" : "",
            "prompt" : "Title", "regex" : "",
            "templated" : false
        }   
      ]
    }
  }
}

_link:
Contains any links associated with the HAL-FORMS document.
_templates:
Contains a collection of template objects. Describes the available state transition details including the HTTP method, message content-type, and arguments for the transition.

Back to the top

Siren

Resources : Kevin Swiber - Siren
Media type : application/vnd.siren+json
Description : Siren is a hypermedia specification for representing entities. As HTML is used for visually representing documents on a Web site, Siren is a specification for presenting entities via a Web API. Siren offers structures to communicate information about entities, actions for executing state transitions, and links for client navigation.
Strengths :

  • More verbose.
  • Query templating.
  • Incorporates actions.

Weaknesses :

  • Lacks documentation.
  • More complex and difficult to implement.

Properties : [ entity , class , properties , property , property key , property value , entities , sub-entities , class , rel , href , type , title , actions , action , name , class , method , href , title , type , fields , name , class , type , value , title , links , link , class , rel , href , type , title ]
Mandatory properties :

  • rel in each entity and link
  • href in each action and link. If a sub-entity is not embedded then href is mandatory in it too.

Siren Document Example:

{
  "class": [ "order" ],
  "properties": { 
      "orderNumber": 42, 
      "itemCount": 3,
      "status": "pending"
  },
  "entities": [
    { 
      "class": [ "items", "collection" ], 
      "rel": [ "http://x.io/rels/order-items" ], //REQUIRED
      "href": "http://api.x.io/orders/42/items" //REQUIRED
    },
    {
      "class": [ "info", "customer" ],
      "rel": [ "http://x.io/rels/customer" ], //REQUIRED
      "properties": { 
        "customerId": "pj123",
        "name": "Peter Joseph"
      },
      "links": [
        { 
            "rel": [ "self" ], //REQUIRED
            "href": "http://api.x.io/customers/pj123" //REQUIRED
        }
      ]
    }
  ],
  "actions": [
    {
      "name": "add-item", //REQUIRED
      "title": "Add Item",
      "method": "POST",
      "href": "http://api.x.io/orders/42/items", //REQUIRED
      "type": "application/x-www-form-urlencoded",
      "fields": [
        { 
            "name": "orderNumber", //REQUIRED
            "type": "hidden", 
            "value": "42" 
        },       
        { 
            "name": "quantity", //REQUIRED
            "type": "number" 
        }
      ]
    }
  ],
  "links": [
    { 
        "rel": [ "self" ], //REQUIRED
        "href": "http://api.x.io/orders/42" 
    },
    { 
        "rel": [ "previous" ], //REQUIRED
         "href": "http://api.x.io/orders/41" 
    },
    { 
        "rel": [ "next" ], //REQUIRED
         "href": "http://api.x.io/orders/43" 
    }
  ]
}

Entities
A collection of related sub-entities. If a sub-entity contains an href value, it should be treated as an embedded link. Clients may choose to optimistically load embedded links. If no href value exists, the sub-entity is an embedded entity representation that contains all the characteristics of a typical entity. One difference is that a sub-entity must contain a rel attribute to describe its relationship to the parent entity.

Back to the top

Collection+JSON

Resources : Collection+JSON - Hypermedia Type
Media type : application/vnd.collection+json

Strengths :

  • Strong choice for collections.
  • Templated queries.
  • Recognized as a standard.

Weaknesses :

  • JSON only.
  • Lack of identifier for documentation.
  • More complex and difficult to implement.

Properties :
Required properties :

Example of Collection+JSON document :

{ "collection" :
  {
    "version" : "1.0",
    "href" : "http://example.org/friends/",
    
    "links" : [
      {"rel" : "feed", "href" : "http://example.org/friends/rss"}
    ],
    
    "items" : [
      {
        "href" : "http://example.org/friends/jdoe",
        "data" : [
          {"name" : "full-name", "value" : "J. Doe", "prompt" : "Full Name"},
          {"name" : "email", "value" : "jdoe@example.org", "prompt" : "Email"}
        ],
        "links" : [
          {"rel" : "blog", "href" : "http://examples.org/blogs/jdoe", "prompt" : "Blog"},
          {"rel" : "avatar", "href" : "http://examples.org/images/jdoe", "prompt" : "Avatar", "render" : "image"}
        ]
      },
      
      {
        "href" : "http://example.org/friends/msmith",
        "data" : [
          {"name" : "full-name", "value" : "M. Smith", "prompt" : "Full Name"},
          {"name" : "email", "value" : "msmith@example.org", "prompt" : "Email"}
        ],
        "links" : [
          {"rel" : "blog", "href" : "http://examples.org/blogs/msmith", "prompt" : "Blog"},
          {"rel" : "avatar", "href" : "http://examples.org/images/msmith", "prompt" : "Avatar", "render" : "image"}
        ]
      },
      
      {
        "href" : "http://example.org/friends/rwilliams",
        "data" : [
          {"name" : "full-name", "value" : "R. Williams", "prompt" : "Full Name"},
          {"name" : "email", "value" : "rwilliams@example.org", "prompt" : "Email"}
        ],
        "links" : [
          {"rel" : "blog", "href" : "http://examples.org/blogs/rwilliams", "prompt" : "Blog"},
          {"rel" : "avatar", "href" : "http://examples.org/images/rwilliams", "prompt" : "Avatar", "render" : "image"}
        ]
      }      
    ],
    
    "queries" : [
      {"rel" : "search", "href" : "http://example.org/friends/search", "prompt" : "Search",
        "data" : [
          {"name" : "search", "value" : ""}
        ]
      }
    ],
    
    "template" : {
      "data" : [
        {"name" : "full-name", "value" : "", "prompt" : "Full Name"},
        {"name" : "email", "value" : "", "prompt" : "Email"},
        {"name" : "blog", "value" : "", "prompt" : "Blog"},
        {"name" : "avatar", "value" : "", "prompt" : "Avatar"}
        
      ]
    }
  } 
}

Query templates :

Consist of a data array associated with an href property. The queries array supports query templates. For query templates, the name/value pairs of the data array set are appended to the URI found in the href property associated with the queries array (with a question-mark ["?"] as separator) and this new URI is sent to the processing agent.

// query template sample
{
  "queries" :
  [
    {
      "href" : "http://example.org/search",
      "rel" : "search",
      "prompt" : "Enter search string",
      "data" :
      [
        {"name" : "search", "value" : ""}
      ]
    }
  ]
}

If the user supplied "JSON" for the value property, the user agent would construct the following URI:

http://example.org/search?search=JSON

Back to the top

Problem+JSON

Status code is optional in the body of the response.

HTTP/1.1 403 Forbidden
Content-Type: application/problem+JSON
Content-Language: en

{
    "type": "http://example.com/probs/out-of-credit",
    "title": "You do not have enough credit.",
    "detail": "Your current balance is 30, but that costs 50.",
    "instance": "http://example.net/account/12345/msgs/abc",
    "balance": 30,
    "accounts": ["http://example.net/account/12345", "http://example.net/account/67890"]
}

Back to the top

Exercises

1. When designing an HTTP based interface, what are the advantages on using idempotent methods versus non idempotent methods?

Idempotent methods can be repeated while producing the same result. For instance:

  • Get always returns the same.
  • Put updates the same resource which remains unaltered after several requests are made.

Non idempotent methods have different results when they are done repeatedly:

  • Post creates a different resource each time is is made.

With this being said, the advantages of using idempotent methods are that these do not change the state of a resource, and therefore, should multiple requests be made, they will always produce the same result.

2. When using a media type specifically designed for error representations, such as problem+json, can the server always respond with a 200 status code, since the error information is contained in the representation?

It can but it definetly should not. Error codes in a response allow for fast interpretation of a response and follow the standard. Although an error code or code information can be attached to body of the message this would require the user to always check the body to determine if the response was actually successfull or not. And even then mistakes could be made since a successful response could be similar to a problem+json one. Of course one could always use content-type to check the type of the answer instead of the code but once again, that is not the standard and would require proper documentation specifying such implementation otherwise most api users would not easily see this implementation detail.

3. Describe two advantages of hypermedia usage on HTTP APIs.
Hypermedia is flexible. It allows resource representation modification or even extensibility without - if used correctly by the client - breaking backwards compatibility.

High api discoverability. Most of the api information resides in it self. The fact that hypermedia resources link to another resources and can describe actions, embedded resources and more permits api transversing in a dynamic fashion.

4. Why can’t the javascript file that defines a NPM module be used directly on a browser, via a script element? What are the transformations done by Webpack that enable this usage?

The problem with modules and the browser resides in the fact that the browser doesn't know how to interpret imports (require for instance) and as such it cannot build a dependency graph or list of the application. Webpack does exactly that, it builds a dependency graph of all the application modules and bundles them up in one or more browser friendly bundle files. These files can be javascript code, css or whatever the code built needs to run effectively.

5. Implement a React component that receives the following properties: an URL, a time interval, and a callback function. This component performs a periodic GET request on the provided URL, using the defined time interval, and presents the last 10 response status codes (or errors) in the DOM, sorted from the most recent to the least recent. If the status code doesn’t represent success (or a response is not received), then the callback function must also be called.

The solution can be found here.

6. In an HTTP request message, what are the differences between the target URI and the method?

TODO

7. In the HTTP protocol, what are the differences between the POST and PUT methods? Describe in which circumstances should each one be used.

TODO

8. In the HTTP protocol, if a response has a non-2xx status code, is the client still allowed to extract any information from the response body?

It depends on the code that is used. Some codes, like 200 (Ok) always have a payload, even if an origin server generates the payload body with zero length. If no payload is desired then a 204 No-Content should be sent. Other responses with no payload could be 205 Reset Content and 201 Created.

9. What is the purpose and structure of the Link HTTP header? In which circumstances should it be used?

The Link header in HTTP allows the server to point an interested client to another resource containing metadata about the requested resource. It allows for the metadata to be given without actually touching the resource in question. Typical uses of the linked metadata file may be to express:

  • A map of different language, content-type and version-specific URIs.
  • Licensing, such as Creative Commons.
  • Information about how to edit the file.
  • Policy information about appropriate use and/or distribution of the data.

10. Describe the semantics and usefulness of the self link relation. Present one usage example.

The value "self" signifies that the URI in the value of the href attribute identifies a resource equivalent to the containing element. One usage might be, if one requests the product orders of a product management api on the target uri http://productmanagementapi.com/orders then the seld link will be:

"self" : {
    "href" : "http://productmanagementapi.com/orders"
}

A client might want to redo a request to the same resource for example to update a view.

11. Implement the javascript function statusForAll(urls) that receives an array of URLs and performs a GET request on each one. It returns a promise that:

  • is fulfilled with an array of status codes, if all requests produced a response with a non-error status code;

  • is rejected when any request fails to produce a response, or the response has an error status code.

The solution can be found here.