Week 3: REST API's
RESTful web applications provide an interface to transfer state through stateless operations.
State in this context means that our backend application will remember previous user interactions. This means that it can provide information to a client about whether or not a user is online.
Let's say you send a http GET request to a REST API on an endpoint like /user/eric
The middlewear will check the sender's credentials, the controller will process this request, it will then query a DB and construct a response with a body of JSON
I sent a request to https://api.github.com/users/ericm and this was the response:
{
"login": "ericm",
"id": 29894839,
"node_id": "MDQ6VXNlcjI5ODk0ODM5",
"avatar_url": "https://avatars3.githubusercontent.com/u/29894839?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ericm",
"html_url": "https://github.com/ericm",
"followers_url": "https://api.github.com/users/ericm/followers",
"following_url": "https://api.github.com/users/ericm/following{/other_user}",
"gists_url": "https://api.github.com/users/ericm/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ericm/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ericm/subscriptions",
"organizations_url": "https://api.github.com/users/ericm/orgs",
"repos_url": "https://api.github.com/users/ericm/repos",
"events_url": "https://api.github.com/users/ericm/events{/privacy}",
"received_events_url": "https://api.github.com/users/ericm/received_events",
"type": "User",
"site_admin": false,
"name": "Eric Moynihan",
"company": null,
"blog": "https://moynihan.io",
"location": "Cork, Ireland",
"email": null,
"hireable": true,
"bio": "CS student at University College Cork.\r\nFreelance Web Developer.\r\nQualified Lifeguard. Profile picture is original artwork.",
"public_repos": 27,
"public_gists": 19,
"followers": 28,
"following": 83,
"created_at": "2017-07-04T14:21:16Z",
"updated_at": "2019-09-19T14:43:57Z"
}
The response was encoded in JSON which allows us to represent JavaScript Objects in plain text.
The process of converting an object into JSON and back again to an object on the client is called serialization.
On a node server we may have an object:
let obj = {a: 1, b: 2};
Now to conver it to JSON:
let response = JSON.stringify(obj);
Then, we'll send this in the body of a HTTP response
Now the client has received the response.
To parse this string, we simpy use the built in method:
let obj = JSON.parse(response_body);
What we have just done is deconstruct and reconstruct a JavaScript object from a server to a client.