Log

REST Vs HTTP

No, REST is the way HTTP should be used.

Today we only use a tiny bit of the HTTP protocol’s methods – namely GET and POST. The REST way to do it is to use all of the protocol’s methods.

For example, REST dictates the usage of DELETE to erase a document (be it a file, state, etc.) behind a URI, whereas, with HTTP, you would misuse a GET or POST query like ...product/?delete_id=22.

Hence HTTP is an application protocol. REST is a service having set of rules, that when followed, enable you to build a distributed application that has a specific set of desirable constraints.

REST = Representational State Transfer

REST is a set of rules, that when followed, enable you to build a distributed application that has a specific set of desirable constraints.

REST is a protocol to exchange any(XML, JSON etc ) messages that can use HTTP to transport those messages.

REST = Representational State Transfer

REST is a set of rules, that when followed, enable you to build a distributed application that has a specific set of desirable constraints.

REST is a protocol to exchange any(XML, JSON etc ) messages that can use HTTP to transport those messages.

Features:

It is stateless which means that ideally no connection should be maintained between the client and server. It is the responsibility of the client to pass its context to the server and then the server can store this context to process the client’s further request. For example, session maintained by server is identified by session identifier passed by the client.

Advantages of Statelessness:

  1. Web Services can treat each method calls separately.
  2. Web Services need not maintain the client’s previous interaction.
  3. This in turn simplifies application design.
  4. HTTP is itself a stateless protocol unlike TCP and thus RESTful Web Services work seamlessly with the HTTP protocols.

Disadvantages of Statelessness:

  1. One extra layer in the form of heading needs to be added to every request to preserve the client’s state.
  2. For security we need to add a header info to every request.

HTTP Methods supported by REST:

GET: /string/someotherstring It is idempotent and should ideally return the same results every time a call is made

PUT: Same like GET. Idempotent and is used to update resources.

POST: should contain a url and body Used for creating resources. Multiple calls should ideally return different results and should create multiple products.

DELETE: Used to delete resources on the server.

HEAD:

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The meta information contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request.

OPTIONS:

This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

HTTP Responses

Go here for all the responses.

Here are a few important ones: 200 – OK 3XX – Additional information needed from the client and url redirection 400 – Bad request
401 – Unauthorized to access
403 – Forbidden
The request was valid, but the server is refusing action. The user might not have the necessary permissions for a resource, or may need an account of some sort.

404 – Not Found
The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.

405 – Method Not Allowed A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.

404 – Request not found
500 – Internal Server Failure
502 – Bad Gateway Error

Advertisements

Javascript Basics – 5

Symbol type

By specification, object property keys may be either of string type, or of symbol type. Not numbers, not booleans, only strings or symbols, these two types.

Till now we’ve only seen strings. Now let’s see the advantages that symbols can give us.

Symbols

“Symbol” value represents an unique identifier with a given name.

A value of this type can be created using Symbol(name):

// id is a symbol with the name “id”

let id = Symbol(“id”);

Symbols are guaranteed to be unique. Even if we create many symbols with the same name, they are different values.

For instance, here are two symbols with the same name – they are not equal:

let id1 = Symbol(“id”);

let id2 = Symbol(“id”);

alert(id1 == id2); // false

Symbols don’t auto-convert to a string

Most values in JavaScript support implicit conversion to a string. For instance, we can alert almost any value, and it will work. Symbols are special. They don’t auto-convert.

For instance, this alert will show an error:

let id = Symbol(“id”);

alert(id); // TypeError: Cannot convert a Symbol value to a string

If we really want to show a symbol, we need to call .toString() on it, like here:

let id = Symbol(“id”);

alert(id.toString()); // Symbol(id), now it works

JavaScript Basics – 4

Reserved words are allowed as property names

A variable cannot have a name equal to one of language-reserved words like “for”, “let”, “return” etc.

But for an object property, there’s no such restriction. Any name is fine:

let obj = {

  for: 1,

  let: 2,

  return: 3

}

alert( obj.for + obj.let + obj.return );  // 6

Basically, any name is allowed, but there’s a special one: “__proto__” that gets special treatment for historical reasons. For instance, we can’t set it to a non-object value:

let obj = {};

obj.__proto__ = 5;

alert(obj.__proto__); // [object Object], didn’t work as intended

Property value shorthand

In real code we often use existing variables as values for property names.

For instance:

function makeUser(name, age) {

  return {

    name: name,

    age: age

    // …other properties

  };

}

let user = makeUser(“John”, 30);

alert(user.name); // John

In the example above, properties have the same names as variables. The use-case of making a property from a variable is so common, that there’s a special property value shorthand to make it shorter.

The “for…in” loop

To walk over all keys of an object, there exists a special form of the loop: for..in. This is a completely different thing from the for(;;) construct that we studied before.

The syntax:

for(key in object) {

  // executes the body for each key among object properties

}

For instance, let’s output all properties of user:

let user = {

  name: “John”,

  age: 30,

  isAdmin: true

};

for(let key in user) {

  // keys

  alert( key );  // name, age, isAdmin

  // values for the keys

  alert( user[key] ); // John, 30, true

}

Ordered like an object

Are objects ordered? In other words, if we loop over an object, do we get all properties in the same order that they are added in it? Can we rely on it?

The short answer is: “ordered in a special fashion”: integer properties are sorted, others appear in creation order. The details follow.

As an example, let’s consider an object with the phone codes:

let codes = {

  “49”: “Germany”,

  “41”: “Switzerland”,

  “44”: “Great Britain”,

  // ..,

  “1”: “USA”

};

for(let code in codes) {

  alert(code); // 1, 41, 44, 49

}

The object may be used to suggest a list of options to the user. If we’re making a site mainly for German audience then we probably want 49 to be the first.

But if we run the code, we see a totally different picture:

  • USA (1) goes first
  • then Switzerland (41) and so on.

So, to fix the issue with the phone codes, we can “cheat” by making the codes non-integer. Adding a plus “+” sign before each code is enough.

Like this:

let codes = {

  “+49”: “Germany”,

  “+41”: “Switzerland”,

  “+44”: “Great Britain”,

  // ..,

  “+1”: “USA”

};

for(let code in codes) {

  alert( +code ); // 49, 41, 44, 1

}

Copying by reference

One of the fundamental differences of objects vs primitives is that they are stored and copied “by reference”.

Primitive values: strings, numbers, booleans – are assigned/copied “as a whole value”.

For instance:

let message = “Hello!”;

let phrase = message;

As a result we have two independent variables, each one is storing the string “Hello!”.

Objects are not like that.

A variable stores not the object itself, but it’s “address in memory”, in other words “a reference” to it.

Here’s the picture for the object:

let user = {

  name: “John”

};

Here, the object is stored somewhere in memory. And the variable user has a “reference” to it.

When an object variable is copied – the reference is copied, the object is not duplicated.

If we imagine an object as a cabinet, then a variable is a key to it. Copying a variable duplicates the key, but not the cabinet itself.

For instance:

let user = { name: “John” };

let admin = user; // copy the reference

Now we have two variables, each one with the reference to the same object:

We can use any variable to access the cabinet and modify its contents:

               

let user = { name: ‘John’ };

let admin = user;

admin.name = ‘Pete’; // changed by the “admin” reference

alert(user.name); // ‘Pete’, changes are seen from the “user” reference

The example above demonstrates that there is only one object. Like if we had a cabinet with two keys and used one of them (admin) to get into it. Then, if we later use the other key (user) we would see changes.

Cloning and merging, Object.assign

So, copying an object variable creates one more reference to the same object.

But what if we need to duplicate an object? Create an independent copy, a clone?

That’s also doable, but a little bit more difficult, because there’s no built-in method for that in JavaScript. Actually, that’s rarely needed. Copying by reference is good most of the time.

But if we really want that, then we need to create a new object and replicate the structure of the existing one by iterating over its properties and copying them on the primitive level.

Like this:

let user = {

  name: “John”,

  age: 30

};

let clone = {}; // the new empty object

// let’s copy all user properties into it

for (let key in user) {

  clone[key] = user[key];

}

// now clone is a fully independant clone

clone.name = “Pete”; // changed the data in it

alert( user.name ); // still John in the original object

Also we can use the method Object.assign for that.

The syntax is:

Object.assign(dest[, src1, src2, src3])

  • Arguments dest, and src1, …, srcN (can be as many as needed) are objects.
  • It copies the properties of all objects src1, …, srcN into dest. In other words, properties of all arguments starting from the 2nd are copied into the 1st. Then it returns dest.

For instance, we can use it to merge several objects into one:

let user = { name: “John” };

let permissions1 = { canView: true };

let permissions2 = { canEdit: true };

// copies all properties from permissions1 and permissions2 into user

Object.assign(user, permissions1, permissions2);

// now user = { name: “John”, canView: true, canEdit: true }

If the receiving object (user) already has the same named property, it will be overwritten:

let user = { name: “John” };

// overwrite name, add isAdmin

Object.assign(user, { name: “Pete”, isAdmin: true });

// now user = { name: “Pete”, isAdmin: true }

We also can use Object.assign to replace the loop for simple cloning:

let user = {

  name: “John”,

  age: 30

};

let clone = Object.assign({}, user);

It copies all properties of user into the empty object and returns it. Actually, the same as the loop, but shorter.