Unit 4
Unit 4
Unit 4
What is Rest
Before we dive into what makes an API RESTful and what constraints and rules you
should follow if you want to create RESTful APIs, let’s explain 2 key terms:
1. Client — the client is the person or software who uses the API. It can be a
developer, for example you, as a developer, can use Twitter API to read and write
data from Twitter, create a new tweet and do more actions in a program that you
write. Your program will call Twitter’s API. The client can also be a web browser.
When you go to Twitter website, your browser is the client who calls Twitter API
and uses the returned data to render information on the screen.
2. Resource — a resource can be any object the API can provide information about.
In Instagram’s API, for example, a resource can be a user, a photo, a hashtag.
Each resource has a unique identifier. The identifier can be a name or a number.
A RESTful web application exposes information about itself in the form of information about
its resources. It also enables the client to take actions on those resources, such as create new
resources (i.e. create a new user) or change existing resources (i.e. edit a post).
In order for your APIs to be RESTful, you have to follow a set of constraints when you write
them. The REST set of constraints will make your APIs easier to use and also easier to
discover, meaning a developer who is just starting to use your APIs will have an easier time
It means when a RESTful API is called, the server will transfer to the client
For example, when a developer calls Instagram API to fetch a specific user (the resource), the
API will return the state of that user, including their name, the number of posts that user
posted on Instagram so far, how many followers they have, and more.
The representation of the state can be in a JSON format, and probably for most APIs this is
What the server does when you, the client, call one of its APIs depends on 2 things that you
1. An identifier for the resource you are interested in. This is the URL for the
resource, also known as the endpoint. In fact, URL stands for Uniform Resource
Locator.
2. The operation you want the server to perform on that resource, in the form of
an HTTP method, or verb. The common HTTP methods are GET, POST, PUT,
and DELETE.
For example, fetching a specific Twitter user, using Twitter’s RESTful API, will require a
URL that identify that user and the HTTP method GET.
Restful Webservices
A web service is a collection of open protocols and standards used for exchanging data between
applications or systems. Software applications written in various programming languages and
running on various platforms can use web services to exchange data over computer networks
like the Internet in a manner similar to inter-process communication on a single computer. This
interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to
the use of open standards.
Web services based on REST Architecture are known as RESTful web services. These
webservices uses HTTP methods to implement the concept of REST architecture. A RESTful
web service usually defines a URI, Uniform Resource Identifier a service, provides resource
representation such as JSON and set of HTTP Methods.
Restful Methods
The below diagram shows mostly all the verbs (POST, GET, PUT, and DELETE) and an
REST API example of what they would mean.
1. POST – This would be used to create a new employee using the RESTful web service
2. GET – This would be used to get a list of all employee using the RESTful web
service
3. PUT – This would be used to update all employee using the RESTful web service
4. DELETE – This would be used to delete all employee using the RESTful services
1. POST – This would not be applicable since we are fetching data of employee 1 which is
already created.
2. GET – This would be used to get the details of the employee with Employee no as 1 using the
RESTful web service
3. PUT – This would be used to update the details of the employee with Employee no as 1 using
the RESTful web service
4. DELETE – This is used to delete the details of the employee with Employee no as 1
Restful Architecture
An application or architecture considered RESTful or REST-style has the following
characteristics
1. State and functionality are divided into distributed resources – This means that every
resource should be accessible via the normal HTTP commands of GET, POST, PUT, or
DELETE. So if someone wanted to get a file from a server, they should be able to issue the
GET request and get the file. If they want to put a file on the server, they should be able to
either issue the POST or PUT request. And finally, if they wanted to delete a file from the
server, they can issue the DELETE request.
Client-server is the typical architecture where the server can be the web server hosting
the application, and the client can be as simple as the web browser.
Stateless means that the state of the application is not maintained in REST. For
example, if you delete a resource from a server using the DELETE command, you
cannot expect that delete information to be passed to the next request.
Uniform Interface
The uniform interface lets the client talk to the server in a single language, independent of the
architectural backend of either. This interface should provide an unchanging, standardized
means of communicating between the client and the server, such as using HTTP with URI
resources, CRUD (Create, Read, Update, Delete) and JSON.
Identifying resources: REST APIs should enable clients to identify a resource by means of a
URI contained within the request;
Manipulation through representations: given the representation of a resource and any metadata
associated with it, the client should be able to modify or delete the resource;
Self-describing messages: the representation of a resource should be returned to the client along
with information on how to process it;
<html>
<head>
<link href="http://www.restful-webservices-cookbook.org/styles/main.css"
rel="stylesheet" type="text/css"/>
<link href="http://www.restful-webservices-cookbook.org/feed"
<p><img src="http://www.restful-webservices-cookbookorg/images/cover"
</p>
</body>
</html>
For strong validation, include either the If-Match or If-None-Match header in a request, and
reference the entity tags (ETag) of the records you want to match against. For weak validation,
include either the If-Modified-Since or If-Unmodified-Since header in a request along with the
date and time you want to check against. The REST API conditional headers follow the HTTP
1.1 specification with the following exceptions.
When you include an invalid header value for If-Match, If-None-Match, or If-
Unmodified-Since on a PATCH or POST request, a 400 Bad Request status code is
returned.
The If-Range header isn’t supported.
DELETE requests are not supported with these headers.
If-None-Match
HTTP 1.1 specification: www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
The If-None-Match header is a request header for sObject Rows that’s the inverse of If-Match.
If the ETag of the record you’re requesting matches an ETag specified in the header, the request
isn’t processed. A 304 Not Modified status code is returned for GET or HEAD requests, and a
412 Precondition Failed status code is returned for PATCH requests.
Supported resources: sObject Rows (Account records only)
Example: If-None-Match: "Jbjuzw7dbhaEG3fd90kJbx6A0ow=-gzip",
"U5iWijwWbQD18jeiXwsqxeGpZQk=-gzip"
If-None-Match
HTTP 1.1 specification: www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
The If-None-Match header is a request header for sObject Rows that’s the inverse of If-Match.
If the ETag of the record you’re requesting matches an ETag specified in the header, the request
isn’t processed. A 304 Not Modified status code is returned for GET or HEAD requests, and a
412 Precondition Failed status code is returned for PATCH requests.
Supported resources: sObject Rows (Account records only)
Example: If-None-Match: "Jbjuzw7dbhaEG3fd90kJbx6A0ow=-gzip",
"U5iWijwWbQD18jeiXwsqxeGpZQk=-gzip"
REACT PART
React Js:
What is React ?
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js"
crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"
crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="mydiv"></div>
<script type="text/babel">
function Show() {
return <h1>My Welcome to Acet </h1>;
}
ReactDOM.render(<Show />, document.getElementById('mydiv'))
</script>
</body>
</html>
React Is a Library
First, the React library is small and it is only used for one part of the job. It doesn’t ship with all of the
tools that you’d expect from a traditional JavaScript framework. A lot of the decisions about which tools
from the ecosystem to use are left up to the developer. Also, new tools emerge all the time, and old ones
are cast aside. There are so many different library names continually being added to the discussion that it
may feel like it’s impossible to keep up.
Think of ECMAScript as Javascript without a host environment. Javascript has two major environments:
browsers and Node.js. These environments add some APIs to the language. An example is
the window object on Browsers and the fs module in Node.js. If you strip all external APIs from these
environments, you get ECMAScript.
ECMAScript 6, also known as ECMAScript 2015, is the latest version of the ECMAScript standard.
ES6 is a significant update to the language, and the first update to the language since ES5 was
standardized in 2009. Implementation of these features in major JavaScript engines is underway now.
In addition to the changes emerging at a language level, there is a lot of momentum around functional
JavaScript programming. JavaScript isn’t necessarily a functional language, but functional techniques
can be used in JavaScript code. React emphasizes functional programming over object-oriented
programming. This shift in thinking can lead to benefits in areas like testability and performance. But
when a lot of React materials assume an understanding of the paradigm, it can be hard to learn so much
at once.
React Features
1. JSX
2. Components
3. One-way Data Binding
4. Virtual DOM
5. Simplicity
6. Performance
JSX
JSX stands for JavaScript XML. It is a JavaScript syntax extension. Its an XML or HTML like syntax
used by ReactJS. This syntax is processed into JavaScript calls of React Framework. It extends the ES6
so that HTML like text can co-exist with JavaScript react code. It is not necessary to use JSX, but it is
recommended to use in ReactJS.
Components
ReactJS is all about components. ReactJS application is made up of multiple components, and each
component has its own logic and controls. These components can be reusable which help you to maintain
the code when working on larger scale projects.
ReactJS is designed in such a manner that follows unidirectional data flow or one-way data binding. The
benefits of one-way data binding give you better control throughout the application. If the data flow is in
another direction, then it requires additional features. It is because components are supposed to be
immutable and the data within them cannot be changed. Flux is a pattern that helps to keep your data
unidirectional. This makes the application more flexible that leads to increase efficiency.
Virtual DOM
A virtual DOM object is a representation of the original DOM object. It works like a one-way data binding.
Whenever any modifications happen in the web application, the entire UI is re-rendered in virtual DOM
representation. Then it checks the difference between the previous DOM representation and new DOM.
Once it has done, the real DOM will update only the things that have actually changed. This makes the
application faster, and there is no wastage of memory.
Simplicity
ReactJS uses JSX file which makes the application simple and to code as well as understand. We know
that ReactJS is a component-based approach which makes the code reusable as your need. This makes it
simple to use and learn.
Performance
ReactJS is known to be a great performer. This feature makes it much better than other frameworks out
there today. The reason behind this is that it manages a virtual DOM. The DOM is a cross-platform and
programming API which deals with HTML, XML or XHTML. The DOM exists entirely in memory. Due
to this, when we create a component, we did not write directly to the DOM. Instead, we are writing virtual
components that will turn into the DOM leading to smoother and faster performance.
Client side we can’t read or write files in javascript front end frame work’s but we can perform
read and write Operations using nodejs methods like fs.readFile() and rs.writeFile()
Event.target.files is an object that contains the details of files selected to be uploaded in a form
there are many third-party packages are available for upload different formats files .for example
we want to upload excel file to server using reactjs we need to install xlsx package.
npm i xlsx
xlsx package provides a bunch of functions for reading and writing CSV/Excel files.
Parsing functions: -
Read Functions: -
Write Functions: -
What Is DOM
First things first, DOM stands for “Document Object Model”. The DOM in simple words
represents the UI of your application. Every time there is a change in the state of your
application UI, the DOM gets updated to represent that change. Now the catch is frequently
manipulating the DOM affects performance, making it slow.
When new elements are added to the UI, a virtual DOM, which is represented as a tree is
created. Each element is a node on this tree. If the state of any of these elements changes, a new
virtual DOM tree is created. This tree is then compared or “diffed” with the previous virtual
DOM tree.
Once this is done, the virtual DOM calculates the best possible method to make these changes to
the real DOM. This ensures that there are minimal operations on the real DOM. Hence, reducing
the performance cost of updating the real DOM.
The image below shows the virtual DOM tree and the diffing process.
The red circles represent the nodes that have changed. These nodes represent the UI elements
that have had their state changed. The difference between the previous version of the virtual
DOM tree and the current virtual DOM tree is then calculated. The whole parent subtree then
gets re-rendered to give the updated UI. This updated tree is then batch updated to the real DOM.
Elements In React :
React elements are different from DOM elements as React elements are simple javascript
objects and are efficient to create.
Rendering an Element in React: In order to render any element into the Browser DOM, we
need to have a container or root DOM element. It is almost a convention to have a div
element with the id=”root” or id=”app” to be used as the root DOM element. Let’s suppose
our index.html file has the following statement inside it.
<div id="root"></div>
Filename App.js: Now, in order to render a simple React Element to the root node, we must
write the following in the App.js file
Now, you have created your first ever React Element and also have rendered it in place, but
React was not developed to create static pages, the intention of using React is to create a more
logical and active webpage. In order to do so, we will need to update the elements.
Updating an Element in React: React Elements are immutable i.e. once an element is created
it is impossible to update its children or attribute. Thus, in order to update an element, we
must use the render() method several times to update the value over time. Let’s see this in an
example.
function showTime()
{
const myElement = (<div><h1>Welcome to GeeksforGeeks!</h1>
<h2>{new Date().toLocaleTimeString()}</h2></div>);
ReactDOM.render(myElement,document.getElementById("root")
);
}
setInterval(showTime, 1000);
In the above example, we have created a function showTime() that displays the current time,
and we have set an interval of 1000ms or 1 sec that recalls the function each second thus
updating the time in each call
React Render Efficiency: React is chosen over the legacy of DOM update because of its
increased efficiency. React achieves this efficiency by using the virtual DOM and efficient
differentiating algorithm. In the example of displaying the current time, at each second we
call the render method, and the virtual DOM gets updated and then the differentiator checks
for the particular differences in Browser DOM and the Virtual DOM and then updates only
what is required such as in the given example the time is the only thing that is getting
changed each time not the title “Welcome to React” thus React only updates the time itself
making it much more efficient than conventional DOM manipulation.
React DOM
ReactDOM is a package that provides DOM specific methods that can be used at the top level
of a web app to enable an efficient way of managing DOM elements of the web page.
ReactDOM provides the developers with an API containing the following methods and a few
more.
render()
findDOMNode()
unmountComponentAtNode()
hydrate()
createPortal()
render() :
This is one of the most important methods of ReactDOM. This function is used to render a
single React Component or several Components wrapped together in a Component or a div
element. This function uses the efficient methods of React for updating the DOM by being
able to change only a subtree, efficient diff methods, etc.
Syntax:
ReactDOM.render(element, container, callback)
Parameters: This method can take a maximum of three parameters as described below.
element: This parameter expects a JSX expression or a React Element to be
rendered.
container: This parameter expects the container in which the element has to be
rendered.
callback: This is an optional parameter that expects a function that is to be
executed once the render is complete.
Return Type: This function returns a reference to the component or null if a stateless
component was rendered.
findDOMNode()
This function is generally used to get the DOM node where a particular React component was
rendered. This method is very less used like the following can be done by adding a ref
attribute to each component itself.
Syntax:
ReactDOM.findDOMNode(component)
Parameters: This method takes a single parameter component that expects a React
Component to be searched in the Browser DOM.
Return Type: This function returns the DOM node where the component was rendered on
success otherwise null.
unmountComponentAtNode()
This function is used to unmount or remove the React Component that was rendered to a
particular container. As an example, you may think of a notification component, after a brief
amount of time it is better to remove the component making the web page more efficient.
Syntax:
ReactDOM.unmountComponentAtNode(container)
Parameters: This method takes a single parameter container which expects the DOM
container from which the React component has to be removed.
Return Type: This function returns true on success otherwise false.
hydrate()
This method is equivalent to the render() method but is implemented while using server-side
rendering.
Syntax:
ReactDOM.hydrate(element, container, callback)
Parameters: This method can take a maximum of three parameters as described below.
element: This parameter expects a JSX expression or a React Component to be
rendered.
container: This parameter expects the container in which the element has to be
rendered.
callback: This is an optional parameter that expects a function that is to be
executed once the render is complete.
Return Type: This function attempts to attach event listeners to the existing markup and
returns a reference to the component or null if a stateless component was rendered.
createPortal()
Usually, when an element is returned from a component’s render method, it’s mounted on the
DOM as a child of the nearest parent node which in some cases may not be desired. Portals
allow us to render a component into a DOM node that resides outside the current DOM
hierarchy of the parent component.
Syntax: ReactDOM.createPortal(child, container)
Parameters: This method takes two parameters as described below.
child: This parameter expects a JSX expression or a React Component to be
rendered.
container: This parameter expects the container in which the element has to be
rendered.
Return Type: This function returns nothing.
React Components
Components are independent and reusable bits of code. They serve the same purpose as
JavaScript functions, but work in isolation and return HTML.
Components come in two types, Class components and Function components, in this tutorial we
will concentrate on Function components.
Class Component
A class component must include the extends React.Component statement. This statement
creates an inheritance to React.Component, and gives your component access to
React.Component's functions.
The component also requires a render() method, this method returns HTML.
Here is the same example as above, but created using a Function component instead.
A Function component also returns HTML, and behaves much the same way as a Class
component, but Function components can be written using much less code, are easier to
understand, and will be preferred in this tutorial.
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
React props :
React Props are like function arguments in JavaScript and attributes in HTML.
To send props into a component, use the same syntax as HTML attributes:
function Car(props) {
DOM Rendering
Render a React element into the DOM in the supplied container and return a reference to the
component (or returns null for stateless components).
If the React element was previously rendered into container, this will perform an update on it
and only mutate the DOM as necessary to reflect the latest React element.
If the optional callback is provided, it will be executed after the component is rendered or
updated.
render() controls the contents of the container node you pass in. Any existing DOM elements
inside are replaced when first called. Later calls use React’s DOM diffing algorithm for
efficient updates.
render() does not modify the container node (only modifies the children of the container). It
may be possible to insert a component to an existing DOM node without overwriting the
existing children.
render() currently returns a reference to the root ReactComponent instance. However, using this
return value is legacy and should be avoided because future versions of React may render
components asynchronously in some cases. If you need a reference to the root ReactComponent
instance, the preferred solution is to attach a callback ref to the root element.
render() method is the only required and most important method of all in-built life-cycle
hooks/methods. In the render() method, we can read props and state and return our JSX
code to the root component of our app. In the render() method, we cannot change the state,
and we cannot cause side effects( such as making an HTTP request to the webserver).
The ReactDOM.render() function takes two arguments, HTML code and an HTML element.
JSX
JSX allows us to write HTML elements in JavaScript and place them in the DOM without
any createElement() and/or appendChild() methods.
root.render(myElement);