UNIT-4: What Is Restful Web Services? Restful Web Services Is A Lightweight, Maintainable, and Scalable
UNIT-4: What Is Restful Web Services? Restful Web Services Is A Lightweight, Maintainable, and Scalable
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.
Why Restful
Restful mostly came into popularity due to the following reasons:
1. Heterogeneous languages and environments – This is one of the
fundamental reasons which is the same as we have seen for SOAP as
well.
Can you imagine the amount of effort to try and code applications on
these devices to talk with normal web applications? Again Restful API’s
can make this job simpler because as mentioned in point no 1, you really
don’t need to know what is the underlying layer for the device.
Restful Architecture
An application or architecture considered RESTful or REST-style has the
following characteristics
1. RESTFul Client-Server
2. Stateless
The concept of stateless means that it’s up to the client to ensure that all
the required information is provided to the server. This is required so that
server can process the response appropriately. The server should not
maintain any sort of information between requests from the client. It’s a
very simple independent question-answer sequence. The client asks a
question, the server answers it appropriately. The client will ask another
question. The server will not remember the previous question-answer
scenario and will need to answer the new question independently.
3. Cache
The Cache concept is to help with the problem of stateless which was
described in the last point. Since each server client request is
independent in nature, sometimes the client might ask the server for the
same request again. This is even though it had already asked for it in the
past. This request will go to the server, and the server will give a
response. This increases the traffic across the network. The cache is a
concept implemented on the client to store requests which have already
been sent to the server. So if the same request is given by the client,
instead of going to the server, it would go to the cache and get the
required information. This saves the amount of to and fro network traffic
from the client to the server.
4. Layered System
5. Interface/Uniform Contract
Tutorialid TutorialName
0 Arrays
1 Queues
2 Stacks
In our REST API tutorial example, we are going to implement the below
Restful Verbs.
1. GET Tutorial – When a client invokes this Restful API, they will be
given the entire set of Tutorials available from the web service.
2. GET Tutorial/Tutorialid – When a client invokes this Restful API,
they will be given the Tutorial name based on the Tutorialid sent by
the client.
3. POST Tutorial/Tutorialname – When a client invokes this Restful
API, the client will submit a request to insert a Tutorialname. The
web service will then add the submitted Tutorial name to the
collection.
4. DELETE Tutorial/Tutorialid– When a client invokes this Restful
API, the client will submit a request to delete a Tutorialname based
on the Tutorialid. The web service will then delete the submitted
Tutorial name from the collection.
Recipe 1.2
There are cases when you may need to forgo visibility to meet
application needs. Use this recipe to find some scenarios.
Recipe 1.3
Recipe 1.4
Recipe 1.5
Recipe 1.6
Use this recipe to learn why custom HTTP methods are not
recommended.
Recipe 1.13
Use this recipe to learn when and how to use custom HTTP
headers.
A context IRI,
a Link Relation Type,
a target IRI,
optionally, target attributes.
Principles
HTTP conditional requests are requests that are executed differently,
depending on the value of specific headers. These headers define a
precondition, and the result of the request will be different if the
precondition is matched or not.
The different behaviors are defined by the method of the request used,
and by the set of headers used for a precondition:
Strong validation
Strong validation consists of guaranteeing that the resource is, byte to
byte, identical to the one it is compared to. This is mandatory for some
conditional headers, and the default for the others. Strong validation is
very strict and may be difficult to guarantee at the server level, but it does
guarantee no data loss at any time, sometimes at the expense of
performance.
It is quite difficult to have a unique identifier for strong validation
with Last-Modified. Often this is done using an ETag with the MD5 hash
of the resource (or a derivative).
Weak validation
Weak validation differs from strong validation, as it considers two
versions of the document as identical if the content is equivalent. For
example, a page that would differ from another only by a different date in
its footer, or different advertising, would be considered identical to the
other with weak validation. These same two versions are
considered different when using strong validation. Building a system of
etags that creates weak validation may be complex, as it involves
knowing the importance of the different elements of a page, but is very
useful towards optimizing cache performance.
Conditional headers
Several HTTP headers, called conditional headers, lead to conditional
requests. These are:
If-Match
If-None-Match
If-Modified-Since
If-Unmodified-Since
If-Range
Similar to If-Match, or If-Unmodified-Since, but can have only
one single etag, or one date. If it fails, the range request fails,
and instead of a 206 Partial Content response, a 200 OK is sent
with the complete resource.
Use cases
Cache update
The most common use case for conditional requests is updating a cache.
With an empty cache, or without a cache, the requested resource is sent
back with a status of 200 OK.
Together with the resource, the validators are sent in the headers. In this
example, both Last-Modified and ETag are sent, but it could equally have
been only one of them. These validators are cached with the resource
(like all headers) and will be used to craft conditional requests, once the
cache becomes stale.
As long as the cache is not stale, no requests are issued at all. But once
it has become stale, this is mostly controlled by the Cache-
Control header, the client doesn't use the cached value directly but
issues a conditional request. The value of the validator is used as a
parameter of the If-Modified-Since and If-Match headers.
If the resource has not changed, the server sends back a 304 Not
Modified response. This makes the cache fresh again, and the client
uses the cached resource. Although there is a response/request round-
trip that consumes some resources, this is more efficient than to transmit
the whole resource over the wire again.
If the resource has changed, the server just sends back a 200
OK response, with the new version of the resource, like if the request
wasn't conditional and the client uses this new resource (and caches it).
ReactJS
Advantage of ReactJS
ReactJS is much easier to learn and use. It comes with a good supply of
documentation, tutorials, and training resources. Any developer who
comes from a JavaScript background can easily understand and start
creating web apps using React in a few days. It is the V(view part) in the
MVC (Model-View-Controller) model, and referred to as ?one of the
JavaScript frameworks.? It is not fully featured but has the advantage of
open-source JavaScript User Interface(UI) library, which helps to
execute the task in a better manner.
History of Java
3. Reusable Components
4. Performance Enhancement
React JS has also gained popularity due to the presence of a handy set
of tools. These tools make the task of the developers understandable
and easier. The React Developer Tools have been designed as Chrome
and Firefox dev extension and allow you to inspect the React component
hierarchies in the virtual DOM. It also allows you to select particular
components and examine and edit their current props and state.
Disadvantage of ReactJS
2. Poor Documentation
3. View Part
ReactJS Covers only the UI Layers of the app and nothing else. So you
still need to choose some other technologies to get a complete tooling
set for development in the project.
4. JSX as a barrier
ReactJS uses JSX. It's a syntax extension that allows HTML with
JavaScript mixed together. This approach has its own benefits, but some
members of the development community consider JSX as a barrier,
especially for new developers. Developers complain about its complexity
in the learning curve.
React Features:
o JSX
o Components
o One-way Data Binding
o Virtual DOM
o Simplicity
o Performance
Future of ReactJS
ReactJS is a declarative, versatile JavaScript framework for building
customizable user interfaces ( UI) with greater simplicity and usability.
An application for various states provides some benefits in generating
basic views and greater convenience in quickly changing and rendering
the related components just as data changes.
React.js is a vital part of the above group and not just a coming and
going system. Released in 2013, the list of the most creative innovations
continues to grow.
Facebook-developed React is an open-source JavaScript framework
that works well for user interface design. Developers use React de to
create interchangeable UI modules and manage display layers for
network and mobile applications. The React development also utilizes
synthetic DOM, the JavaScript object. It increases the efficiency of apps
since the DOM of JS is quicker than the standard one.
In modern JavaScript creation, React.js is one of the most
developmentally important frontend libraries you can use. It helps you to
create highly reactive user interfaces that have a user experience that is
fast and mobile-app-like.
As a developer, you concentrate on creating modules in a declarative
fashion while operating with React (i.e., you decide how it should look,
not how it should get there), and React will take care of the rest. You can
rely on its quick and streamlined internal rendering process and thus
have an excellent experience for your users.
With minimal code, it is primarily intended to quickly and reliably create
rich and engaging mobile applications.
Instead of a full web app, React JS gives the ability to function on
individual components, which allows them to have the best possible
rendering output.
React development has emerged as the future of web creation with its
extra versatility and ease. Issues linked.
Over 94000 pages are estimated to use ReactJS, and more than 1300
developers are actively using ReactJS for development.
Facebook, PayPal, Instagram, Uber, and Airbnb are the most famous
examples of the use of ReactJS.
In web development, new frameworks are starting to be built to resolve
the libraries' limitations or frameworks before them. ReactJS has
overcome many of the shortcomings of prior implementations like
AngularJS. It is used to develop fast and scalable web applications, and
new plugins are designed for ReactJS as soon as the need for additional
functionality increases.
ReactJS developers have a bright future ahead as the technology is in
use in several industries. In fact, as opposed to other Web development
technology, React developers are now paying the most.
If you have an in-depth knowledge of JavaScript and even HTML5 to
work with React, it will help. JS, which would be beneficial, which is
similar when dealing with JSX.
You will be able to function both on the client-side and the server-side. It
will facilitate the development of larger applications with its portion and
data patterns that improve readability.
Thanks to its versatility, increased performance, and improved usability
features, it is an outstanding frontend development program.
Facebook and the whole ReactJS team have shown the commitment to
improving the efficiency of ReactJS. This is important for the increasingly
emerging competition from other systems such as Vue.js to be resolved.
Any of the considerations to remember are server-side rendering
extension in upcoming releases. A redesigned server rendering comes
with the latest ReactJS that makes it very fast and streamable. It's a
great spot to refine the presentation.
Developers also await a rise in the handling of errors. In the past, during
rendering, runtime errors sometimes put ReactJS in an awkward, broken
state. This also involves refreshing the page. The established model of
resolving the error is thrown inside the part or lifecycle processes.
Although this helps avoid the corrupt rendering of results, the improved
UX is not the right idea.
ReactJS experts should expect fresh ways of rendering. For starters, the
ReactJS team is likely to add a special fragment syntax to the JSX that
needs no keys.
Learning the development of "ReactJS" makes perfect sense because it
provides developers with much-needed simplicity in considerably less
time to produce highly immersive mobile apps and user interfaces. They
design large-scale applications with continuously evolving data. The
advantages of being modular, scalable, agile, non-risky, user-friendly
greatly outweigh the disadvantages of developers and organizations.
React is easy to use for programmers, ensuring businesses are
effectively deploying their projects and being more profitable. The
platform of React.js revolutionizes the way the frontend is handled. By
offering a View UI and a storage layer, it addresses the view issue. It will
connect to an API-like backend that uses routers, controllers, and
templates to access data and execute backend logic.
It was ingenious for Facebook to create a framework for UI rendering; it
is simple, easy to get used to, and instrumental. React resolves the
display problem by building a UI and a data layer on the Display. It will
use routers, controllers, and models to communicate with an API-like
backend that accesses data and implements back-end logic.
Developers write programs to React in terms of "Components." And if it's
too intricate a component, don't worry. We're going to break it up into
smaller, more manageable, reusable pieces!
Working with the files:
Select a File (user input): To enable the user to pick a file, the
first step is to add the tag to our App component. This tag should
have the type attribute set as “file”. Now, we need an event
handler to listen to any changes made to the file. This event
handler will be triggered whenever the user selects a new file and
will update the state.
Send a request to the server: After storing the selected file (in
the state), we are now required to send it to a server. For this
purpose, we can use fetch or Axios. (In this code, we use Axios a
promise-based HTTP client for the browser and NodeJS). The file
is sent to the service wrapped in a FormData object.
ReactJS Pure Components
Generally, In ReactJS, we use shouldComponentUpdate() Lifecycle
method to customize the default behavior and implement it when the
React component should re-render or update itself.
Prerequisite:
ReactJS Components
ReactJS Components – Set 2
Now, ReactJS has provided us a Pure Component. If we extend a
class with Pure Component, there is no need
for shouldComponentUpdate() Lifecycle Method. ReactJS Pure
Component Class compares current state and props with new props
and states to decide whether the React component should re-render
itself or Not.
In simple words, If the previous value of state or props and the new
value of state or props is the same, the component will not re-render
itself. Since Pure Components restricts the re-rendering when there is
no use of re-rendering of the component. Pure Components are Class
Components which extends React.PureComponent.
Example: Program to demonstrate the creation of Pure Components.
javascript
render(){
}
}
Output :
78
51
I have created a single page web app using react js. I have
used webpack to create bundle of all components. But now I want to
create many other pages. Most of pages are API call related. i.e. in
the index.html, I have displayed content from API. I want to insert
content in another page parsing data from API. Webpack compresses
everything of react in a file which is bundle.js. However, the configuration
of webpack is as follow:
output: {
path:'./',
filename: 'dist/bundle.js',
},
devServer: {
inline: true,
port: 3000
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
Virtual DOM
DOM: DOM stands for ‘Document Object Model’. In simple terms, it is a
structured representation of the HTML elements that are present in a
webpage or web-app. DOM represents the entire UI of your application.
The DOM is represented as a tree data structure. It contains a node for
each UI element present in the web document. It is very useful as it
allows web developers to modify content through JavaScript, also it
being in structured format helps a lot as we can choose specific targets
and all the code becomes much easier to work with. If you want to learn
more about DOM, visit this link.
Updating DOM: If you know a little about JavaScript then you might
have seen people making use of ‘getElementById()’ or
‘getElementByClass()’ method to modify the content of DOM. Every
time there is a change in the state of your application, the DOM get’s
updated to reflect that change in the UI. Though doing things like this is
not a problem and it works fine, but consider a case where we have a
DOM that contains nodes in a large number, and also all these web
elements have different styling and attributes. As DOM is represented
as a tree itself, updating the tree here is not a costly operation indeed
we have a lot of algorithms on trees to make the updates fast. What’s
proving to be costly is everytime the DOM gets updated, the updated
element and it’s children have to be rendered again to update the UI of
our page. Like this each time there is a component update, the DOM
needs to be updated and the UI components have to be re-rendered.
Example:
javascript
When writing the above code in the console or in the JavaScript file,
these things happen:
The browser parses the HTML to find the node with this id.
It removes the child element of this specific element.
Updates the element(DOM) with the ‘updated value’.
Recalculates the CSS for the parent and child nodes.
Update the layout.
Finally, traverse the tree and paint it on the screen(browser) display.
So as we know now that updating the DOM not only involves changing
the content, it has a lot more attached to it. Also recalculating the CSS
and changing the layouts involves complex algorithms, and they do
affect the performance. So React has a different approach to dealing
with this, as it makes use of something known as Virtual DOM.
Virtual DOM: React uses Virtual DOM exists which is like a lightweight
copy of the actual DOM(a virtual representation of the DOM). So for
every object that exists in the original DOM, there is an object for that in
React Virtual DOM. It is exactly the same, but it does not have the
power to directly change the layout of the document. Manipulating DOM
is slow, but manipulating Virtual DOM is fast as nothing gets drawn on
the screen. So each time there is a change in the state of our
application, virtual DOM gets updated first instead of the real DOM.
You may still wonder, “Aren’t we doing the same thing again and
doubling our work? How can this be faster?” Read below to understand
how things will be faster using virtual DOM.
ReactDOM.hydrate(element,container[ ,callback])
React expects that the rendered content is identical between the server
and the client. It can patch up differences in text content, but you should
treat mismatches as bugs and fix them. In development mode, React
warns about mismatches during hydration. There are no guarantees that
attribute differences will be patched up in case of mismatches. This is
important for performance reasons because in most apps, mismatches
are rare, and so validating all markup would be prohibitively expensive.
If a single element’s attribute or text content is unavoidably different
between the server and the client (for example, a timestamp), you may
silence the warning by adding suppressHydrationWarning={true} to the
element. It only works one level deep, and is intended to be an escape
hatch. Don’t overuse it. Unless it’s text content, React still won’t attempt
to patch it up, so it may remain inconsistent until future updates.
If you intentionally need to render something different on the server and
the client, you can do a two-pass rendering. Components that render
something different on the client can read a state variable
like this.state.isClient, which you can set
to true in componentDidMount(). This way the initial render pass will
render the same content as the server, avoiding mismatches, but an
additional pass will happen synchronously right after hydration. Note that
this approach will make your components slower because they have to
render twice, so use it with caution.
unmountComponentAtNode()
ReactDOM.unmountComponentAtNode(container)
Remove a mounted React component from the DOM and clean up its
event handlers and state. If no component was mounted in the
container, calling this function does nothing. Returns true if a component
was unmounted and false if there was no component to unmount.
findDOMNode()
ReactDOM.findDOMNode(component)
If this component has been mounted into the DOM, this returns the
corresponding native browser DOM element. This method is useful for
reading values out of the DOM, such as form field values and performing
DOM measurements. In most cases, you can attach a ref to the DOM
node and avoid using findDOMNode at all.
When a component renders to null or false, findDOMNode returns null.
When a component renders to a string, findDOMNode returns a text
DOM node containing that value. As of React 16, a component may
return a fragment with multiple children, in which case findDOMNode will
return the DOM node corresponding to the first non-empty child.
createPortal()
ReactDOM.createPortal(child,container)
Step 4 − Check the Data element radio button on the CREATE TYPE
pop-up that appears with three radio buttons.
Step 5 − Click the green checkmark icon. You are directed to
the maintenance screen of the data element.
Step 6 − Enter the description in the short text field of the
maintenance screen of the data element. In this case, it is
“Customer Data Element”. Note − You cannot enter any other
attribute until you have entered this attribute.
Step 7 − Assign the data element with the type. You can create an
elementary data element by checking elementary type or a reference
data element by checking Reference type. You can assign a data
element to a Domain or Predefined Type within Elementary Type and
with Name of Reference Type or Reference to Predefined Type within
Reference Type.
Step 8 − Enter the fields for short text, medium text, long text, and
heading in the Field Label tab. You can press Enter and the length is
automatically generated for these labels.
Step 9 − Save your changes. The Create Object Directory Entry pop-up
appears and asks for a package. You may enter the package name in
which you are working. If you do not have any package then you may
create it in the Object Navigator or you can save your data element
using the Local Object button.
Step 10 − Activate your data element. Click the Activate icon
(matchstick icon) or press CTRL + F3 to activate the data element. A
pop-up window appears, listing the 2 currently inactive objects as
shown in the following screenshot.
Step 11 − At this point, the top entry labeled ‘DTEL’ with the name
Z_CUST is to be activated. As this is highlighted, click the green tick
button. This window disappears and the status bar will display the
message ‘Object activated’.
If error messages or warnings occurred when you activated the data
element, the activation log is displayed automatically. The activation log
displays information about activation flow. You can also call the
activation log with Utilities(M) → Activation log.
React.Component
React lets you define components as classes or functions. Components
defined as classes currently provide more features which are described
in detail on this page. To define a React component class, you need to
extend React.Component:
render(){
return<h1>Hello, {this.props.name}</h1>
Since every HTML element has different properties, the Node object will
be created from different classes (constructor functions). For example,
the Node object for the div element is created
from HTMLDivElement which inherits Node class. For our earlier HTML
document, we can visualize these nodes using a simple test as below.
The browser comes with built-in classes
like HTMLDivElement, HTMLScriptElement, Node etc.
After the browser has created Nodes from the HTML document, it has to
create a tree-like structure of these node objects. Since our HTML
elements in the HTML file are nested inside each other, the browser
needs to replicate that but using Node objects it has previously created.
This will help the browser efficiently render and manage the webpage
throughout its lifecycle.
(DOM Tree)
A DOM tree for our earlier HTML document looks like above. A DOM tree
starts from the topmost element which is html element and branches out
as per the occurrence and nesting of HTML elements in the document.
Whenever an HTML element is found, it creates a DOM node (Node)
object from its respective class (constructor function).
💡 A DOM node doesn’t always have to be an HTML element. When the
browser creates a DOM tree, it also saves things
like comments, attributes, text as separate nodes in the tree. But for the
simplicity, we will just consider DOM nodes for HTML elements
AKA DOM element. Here is the list of all DOM node types.
You can visualize the DOM tree in Google Chrome DevTools
Console as shown below. This will show you the hierarchy of DOM
elements (a high-level view of DOM tree) with properties of each DOM
element.
Let’s say, for our earlier example, we are going to use the below CSS
styles (this is not the CSS used for the card shown in the screenshot).
For the sake of simplicity, we are not going to be bothered about how we
are importing the CSS styles in the HTML page.
(source: gist.github.com)
After constructing the DOM, the browser reads CSS from all the sources
(external, embedded, inline, user-agent, etc.) and construct a CSSOM.
CSSOM stands for CSS Object Model which is a Tree Like structure just
like DOM.
Each node in this tree contains CSS style information that will be applied
to DOM elements that it target (specified by the selector). CSSOM,
however, does not contain DOM elements which can’t be printed on the
screen like <meta>, <script>, <title> etc.
As we know, most of the browser comes with its own stylesheet which is
called as user agent stylesheet, the browser first computes final CSS
properties for DOM element by overriding user agent styles with CSS
provided by the developer properties (using specificity rules) and then
construct a node.