Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

React

what is react js?


React is an open-source front-end JavaScript library for building user interfaces or UI components. It is
maintained by Facebook and a community of individual developers and companies. React can be used as
a base in the development of single-page or mobile applications.

1. What are the advantages of using React?


MVC is generally abbreviated as Model View Controller.

i. It increases the application’s performance


ii. It can be conveniently used on the client as well as server side
iii. Because of JSX, code’s readability increases
iv. React is easy to integrate with other frameworks like Meteor, Angular, etc
v. Using React, writing UI test cases become extremely easy
 Use of Virtual DOM to improve efficiency
React uses virtual DOM to render the view. As the name suggests, virtual DOM is a virtual
representation of the real DOM. Each time the data changes in a react app, a new virtual DOM
gets created. Creating a virtual DOM is much faster than rendering the UI inside the browser.
Therefore, with the use of virtual DOM, the efficiency of the app improves.
 Gentle learning curve
React has a gentle learning curve when compared to frameworks like Angular. Anyone with little
knowledge of javascript can start building web applications using React.
 SEO friendly
React allows developers to develop engaging user interfaces that can be easily navigated in
various search engines. It also allows server-side rendering, which boosts the SEO of an app.
 Reusable components
React uses component-based architecture for developing applications. Components are
independent and reusable bits of code. These components can be shared across various
applications having similar functionality. The re-use of components increases the pace of
development.
 Huge ecosystem of libraries to choose from
React provides you the freedom to choose the tools, libraries, and architecture for developing
an application based on your requirement.

2. What is JSX?
JSX stands for JavaScript XML.
It allows us to write HTML inside JavaScript and place them in the DOM without using functions like
appendChild( ) or createElement( ).
As stated in the official docs of React, JSX provides syntactic sugar for React.createElement( ) function.
**Note- We can create react applications without using JSX as well.
Let’s understand how JSX works:

Without using JSX, we would have to create an element by the following process:
const text = React.createElement('p', {}, 'This is a text');
const container = React.createElement('div','{}',text );
ReactDOM.render(container,rootElement);
Using JSX, the above code can be simplified:
const container = (
<div>
<p>This is a text</p>
</div>
);
ReactDOM.render(container,rootElement);

As one can see in the code above, we are directly using HTML inside JavaScript.

3. What are the differences between functional and class components?


Before the introduction of Hooks in React, functional components were called stateless components and
were behind class components on feature basis. After the introduction of Hooks, functional components
are equivalent to class components.
Although functional components are the new trend, the react team insists on keeping class components
in React. Therefore, it is important to know how these both components differ.
On the following basis let’s compare functional and class components:

Decalaration
Functional components are nothing but JavaScript functions and therefore can be declared using
an arrow function or the function keyword:
 function card(props){
 return(
 <div className="main-container">
 <h2>Title of the card</h2>
 </div>
 )
 }

 const card = (props) =>{
 return(
 <div className="main-container">
 <h2>Title of the card</h2>
 </div>
 )
 }

Class components on the other hand, are declared using the ES6 class:
class Card extends React.Component{
constructor(props){
super(props);
}

render(){
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
}

Handling props
Let’s render the following component with props and analyse how functional and class components
handle props:
 <StudentInfo name="Vivek" rollNumber="23" />
In functional components, the handling of props is pretty straight forward. Any prop provided as an
argument to a functional component, can be directly used inside HTML elements:
function StudentInfo(props){
return(
<div className="main">
<h2>{props.name}</h2>
<h4>{props.rollNumber}</h4>
</div>
)
}

In the case of class components, props are handled in a different way:

class StudentInfo extends React.Component{


constructor(props){
super(props);
}

render(){
return(
<div className="main">
<h2>{this.props.name}</h2>
<h4>{this.props.rollNumber}</h4>
</div>
)
}
}

As we can see in the code above, this keyword is used in the case of class components.

Handling state
Functional components use React hooks to handle state.
It uses the useState hook to set state of a variable inside the component:

 function ClassRoom(props){
 let [studentsCount,setStudentsCount] = useState(0);

 const addStudent = () => {
 setStudentsCount(++studentsCount);
 }
 return(
 <div>
 <p>Number of students in class room: {studentsCount}</p>
 <button onClick={addStudent}>Add Student</button>
 </div>
 )
 }

4. What is the virtual DOM? How does react use the virtual DOM to render the UI?
As stated by the react team, virtual DOM is a concept where a virtual representation of the real DOM is
kept inside the memory and is synced with the real DOM by a library such as ReactDOM.

Why was virtual DOM introduced? DOM manipulation is an integral part of any web application, but
DOM manipulation is quite slow when compared to other operations in JavaScript.
The efficiency of the application gets affected when several DOM manipulations are being done. Most
JavaScript frameworks update the entire DOM even when a small part of the DOM changes.
For example, consider a list that is being rendered inside the DOM. If one of the items in the list
changes, the entire list gets rendered again instead of just rendering the item that was
changed/updated. This is called inefficient updating.
To address the problem of inefficient updating, the react team introduced the concept of virtual DOM.

How does it work?

For every DOM object, there is a corresponding virtual DOM object(copy), which has the same properties.
The main difference between the real DOM object and the virtual DOM object is that any changes in the virtual DOM object will not reflect on the
screen directly. Consider a virtual DOM object as a blueprint of the real DOM object.
Whenever a JSX element gets rendered, every virtual DOM object gets updated.

**Note- One may think updating every virtual DOM object might be inefficient, but that’s not the case. Updating the virtual DOM is much
faster than updating the real DOM since we are just updating the blueprint of the real DOM.

React uses two virtual DOMs to render the user interface. One of them is used to store the current state of the objects and the other to store the
previous state of the objects.
Whenever the virtual DOM gets updated, react compares the two virtual DOMs and gets to know about which virtual DOM objects were updated.
After knowing which objects were updated, react renders only those objects inside the real DOM instead of rendering the complete real DOM.
This way, with the use of virtual DOM, react solves the problem of inefficient updating.

5. What are the differences between controlled and uncontrolled components?


Controlled and uncontrolled components are just different approaches to handling input form elements in react.
Feature Uncontrolled Controlled Name attrs
One-time value retrieval (e.g. on submit) ✔️ ✔️ ✔️
Validating on submit ✔️ ✔️ ✔️
Field-level Validation ❌ ✔️ ✔️
Conditionally disabling submit button ❌ ✔️ ✔️
Enforcing input format ❌ ✔️ ✔️
several inputs for one piece of data ❌ ✔️ ✔️
dynamic inputs ❌ ✔️ ❌

Controlled component In a controlled component, the value of the input element is controlled by React.
We store the state of the input element inside the code, and by using event-based callbacks, any
changes made to the input element will be reflected in the code as well.
When a user enters data inside the input element of a controlled component, onChange function gets
triggered and inside the code we check whether the value entered is valid or invalid. If the value is valid,
we change the state and re-render the input element with new value.
Example of a controlled component:
function FormValidation(props) {
let [inputValue, setInputValue] = useState("");

let updateInput = e => {


setInputValue(e.target.value);
};

return (
<div>
<form>
<input type="text" value={inputValue} onChange={updateInput} />
</form>
</div>
);
}
As one can see in the code above, the value of the input element is determined by the state of
the inputValue variable. Any changes made to the input element is handled by
the updateInput function.

Uncontrolled component In an uncontrolled component, the value of the input element is handled by
the DOM itself.
Input elements inside uncontrolled components work just like normal HTML input form elements.
The state of the input element is handled by the DOM. Whenever the value of the input element is
changed,event-based callbacks are not called. Basically, react does not perform any action when there
are changes made to the input element.
Whenever use enters data inside the input field, the updated data is shown directly. To access the value
of the input element, we can use ref.
Example of an uncontrolled component:
function FormValidation(props) {
let inputValue = React.createRef();

let handleSubmit = e => {


alert(`Input value: ${inputValue.current.value}`);
e.preventDefault();
};

return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" ref={inputValue} />
<button type="submit">Submit</button>
</form>
</div>
);
}

As one can see in the code above, we are not using onChange function to govern the changes made to the input element. Instead, we are using ref to
access the value of the input element.

6. What are the different lifecycle methods in React?


Every component in React has lifecycle methods that we can tap into, to trigger changes at a particular
phase of the life cycle.
Each component in react goes through three phases: Mounting, Updating, and Unmounting.
There are corresponding lifecycle methods for each of the three phases:

**Note- In this article, we are discussing the use of lifecycle methods in class components. For utilising
lifecycle methods in functional components, react hooks are used.

Mounting:

There are four built-in lifecycle methods that are called in the following order when a component is mounted:
constructor( ) - This is called before anything else. We can set the initial state of the component inside this method. The constructor method is used to
set the initial state and bind methods to the component.
getDerivedStateFromProps( ) - This is called before rendering the elements in the DOM.
In this method, we can set the state of the component based on the props we received. This method is used very rarely.
render( ) - This is the only required method in the class component. This method returns the HTML elements which are going to be rendered inside the
DOM.
componentDidMount( ) - It is called right after the component is rendered inside the DOM. All the statements which require the DOM nodes can be
executed in this method. Network requests from a remote end-point can also be instantiated in this method.

Updating:

Updates in react are caused by changes in state or props. Update leads to re-rendering of the component. The following methods are called when a
component is re-rendered:
getDerivedStateFromProps( ) - This method is called again when a component is being re-rendered.
shouldComponentUpdate( ) - This method is called before rendering the component when new props are received. It lets React know if the
component’s output is affected by the newly received props or by the state change. By default, it returns true.
render( ) - To re-render the HTML inside the DOM, the render( ) method gets called again.
getSnapshotBeforeUpdate( ) - This method is called just before the newly rendered HTML gets committed to the DOM. It stores the previous state of
the component so that React has an idea of what parts of the DOM needs to be updated.
componentDidUpdate( ) - It is called after the component gets re-rendered. This method works just like the componentDidMount( ) method, the
difference is that this method does not get called on initial render.

Unmounting:

componentWillUnmount( ) - This method is called just before the component gets destroyed. Any clean up statements should be executed inside this
method.

7. Explain Strict Mode in React.

StrictMode is a tool added in the version 16.3 of React to highlight potential problems in an application.
It performs additional checks on the application.

function App() {
return (
<React.StrictMode>
<div classname="App">
<Header/>
<div>
Page Content
</div>
<Footer/>
</div>
</React.StrictMode>
);
}

To enable StrictMode, <React.StrictMode> tags need to be added inside the application:


import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");


ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);

StrictMode currently helps with the following issues:


Identifying components with unsafe lifecycle methods
Certain lifecycle methods are unsafe to use in asynchronous react applications. With the use of third-
party libraries it becomes difficult to ensure that certain lifecycle methods are not used.
StrictMode helps in providing us a warning if any of the class components uses an unsafe lifecycle
method.
Warning about the usage of legacy string API
If one is using an older version of React, callback ref is the recommended way to manage refs instead of
using the string refs. StrictMode gives a warning if we are using string refs to manage refs.

Warning about the usage of findDOMNode


Previously, findDOMNode( ) method was used to search the tree of a DOM node. This method is
deprecated in React. Hence, the StrictMode gives us a warning about the usage of this method.
Warning about the usage of legacy context API (because the API is error-prone)

8. How to prevent re-renders in React?

Reason for re-renders in React:


Re-rendering of a component and it’s child components occur when props or state of the component
has been changed.
Re-rendering components that are not updated, affects the performance of an application.
How to prevent re-rendering:
Consider the following components:

class Parent extends React.Component {


state = { messageDisplayed: false };
componentDidMount() {
this.setState({ messageDisplayed: true });
}

render() {
console.log("Parent is getting rendered" );
return (
<div className="App">
<Message />
</div>
);
}
}

class Message extends React.Component {


constructor(props) {
super(props);
this.state = { message: "Hello, this is vivek" };
}
render() {
console.log("Message is getting rendered");
return (
<div>
<p>{this.state.message}</p>
</div>
);
}
}

Parent component is the parent component and Message is the child component. Any change in the
parent component will lead to re-rendering of the child component as well.
To prevent the re-rendering of child component, we use the shouldComponentUpdate( ) method:

**Note- Use shouldComponentUpdate( ) method only when you are sure that it’s a static component.
class Message extends React.Component {
constructor(props) {
super(props);
this.state = { message: "Hello, this is vivek" };
}
shouldComponentUpdate() {
console.log("Does not get rendered");
return false;
}
render() {
console.log("Message is getting rendered");
return (
<div>
<p>{this.state.message}</p>
</div>
);
}
}

As one can see in the code above, we have returned false from the shouldComponentUpdate( ) method, which prevents the child component from re-
rendering.

9. Explain React state and props.


Props State
Immutable Owned by its component
Has better performance Locally scoped
Can be passed to child components Witeable/Mutable
has setState() method to modify properties
Changes to state can be asynchronous
can only be passed as props

React State
Every component in react has a built-in state object, which contains all the property values that belong
to that component.
In other words, the state object controls the behaviour of a component. Any change in the property
values of the state object leads to re-rendering of the component.

**Note- State object is not available in functional components but, we can use React Hooks to add
state to a functional component.

How to declare a state object?


Example:
class Car extends React.Component{
constructor(props){
super(props);
this.state = {
brand: "BMW",
color: "black"
}
}
}

How to use and update the state object?


class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: "BMW",
color: "Black"
};
}

changeColor() {
this.setState(prevState => {
return { color: "Red" };
});
}

render() {
return (
<div>
<button onClick={() => this.changeColor()}>Change Color</button>
<p>{this.state.color}</p>
</div>
);
}
}

As one can see in the code above, we can use the state by calling this.state.propertyName and we can change the state object property
using setState method.
React Props
Every react component, accepts a single object argument called props (which stands for “properties”).
These props can be passed to a component using HTML attributes and the component accepts these props as an argument.
Using props, we can pass data from one component to another.
Passing props to a component:
While rendering a component, we can pass the props as a HTML attribute:
<Car brand="Mercedes"/>

The component receives the props:


In Class component:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {
brand: this.props.brand,
color: "Black"
};
}
}

In Functional component:
function Car(props) {
let [brand, setBrand] = useState(props.brand);
}

****Note- Props are read-only. They cannot be manipulated or changed inside a component.

10. Explain React Hooks.


What are Hooks? Hooks are functions that let us “hook into” React state and lifecycle features from a
functional component.
React Hooks cannot be used in class components. They let us write components without class.
Why were Hooks introduced in React?
React hooks were introduced in the 16.8 version of React.
Previously, functional components were called stateless components. Only class components were used for state management and lifecycle methods.
The need to change a functional component to a class component, whenever state management or lifecycle methods were to be used, led to the development of
Hooks.
Example of a hook:
useState hook:
In functional components, useState hook lets us define state for a component:
function Person(props) {
// We are declaring a state variable called name.
// setName is a function to update/change the value of name
let [name, setName] = useState('');
}

The state variable “name” can be directly used inside the HTML.

11. What are the different ways to style a React component?


There are many different ways through which one can style a React component. Some of the ways are :
Inline Styling
We can directly style an element using inline style attributes.
Make sure the value of style is a JavaScript object:
 class RandomComponent extends React.Component {
 render() {
 return (
 <div>
 <h3 style={{ color: "Yellow" }}>This is a heading</h3>
 <p style={{ fontSize: "32px" }}>This is a paragraph</p>
 </div>
 );
 }
 }

Using JavaScript object


We can create a separate JavaScript object and set the desired style properties.
This object can be used as the value of the inline style attribute.
 class RandomComponent extends React.Component {
 paragraphStyles = {
 color: "Red",
 fontSize: "32px"
 };

 headingStyles = {
 color: "blue",
 fontSize: "48px"
 };

 render() {
 return (
 <div>
 <h3 style={this.headingStyles}>This is a heading</h3>
 <p style={this.paragraphStyles}>This is a paragraph</p>
 </div>
 );
 }
 }

CSS Stylesheet
We can create a separate CSS file and write all the styles for the component inside that file. This file
needs to be imported inside the component file.
 import './RandomComponent.css';

 class RandomComponent extends React.Component {
 render() {
 return (
 <div>
 <h3 className="heading">This is a heading</h3>
 <p className="paragraph">This is a paragraph</p>
 </div>
 );
 }
 }

CSS Modules
We can create a separate CSS module and import this module inside our component. Create a file with
“.module.css”‘ extension,
styles.module.css:
 .paragraph{
 color:"red";
 border:1px solid black;
 }

We can import this file inside the component and use it:
import styles from './styles.module.css';

class RandomComponent extends React.Component {


render() {
return (
<div>
<h3 className="heading">This is a heading</h3>
<p className={styles.paragraph} >This is a paragraph</p>
</div>
);
}
}

12. Name a few techniques to optimize React app performance.


There are many ways through which one can optimize the performance of a React app, let’s have a look at some of them:

 Using useMemo( ) -
It is a React hook that is used for caching CPU-Expensive functions.
Sometimes in a React app, a CPU-Expensive function gets called repeatedly due to re-renders of a component, which can lead to slow rendering.
useMemo( ) hook can be used to cache such functions. By using useMemo( ), the CPU-Expensive function gets called only when it is needed.

 Using React.PureComponent -
It is a base component class that checks state and props of a component to know whether the component should be updated.
Instead of using the simple React.Component, we can use React.PureComponent to reduce the re-renders of a component unnecessarily.

 Maintaining State Colocation -


This is a process of moving the state as close to where you need it as possible.
Sometimes in React app, we have a lot of unnecessary states inside the parent component which makes the code less readable and harder to
maintain. Not to forget, having many states inside a single component leads to unnecessary re-renders for the component.
It is better to shift states which are less valuable to the parent component, to a separate component.

 Lazy Loading -
It is a technique used to reduce the load time of a React app. Lazy loading helps reduce the risk of web app performances to minimal.

13. What are keys in React?

A key is a special string attribute that needs to be included when using lists of elements.
Example of a list using key:
const ids = [1,2,3,4,5];
const listElements = ids.map((id)=>{
return(
<li key={id.toString()}>
{id}
</li>
)
})

Importance of keys
Keys help react identify which elements were added, changed or removed.
Keys should be given to array elements for providing a unique identity for each element.
Without keys, React does not understand the order or uniqueness of each element.
With keys, React has an idea of which particular element was deleted,edited, and added.
Keys are generally used for displaying a list of data coming from an API.
***Note- Keys used within arrays should be unique among siblings. They need not be globally unique.

14. How to pass data between react components?

Parent Component to Child Component (using props)


With the help of props, we can send data from a parent to a child component.
How do we do this?

Consider the following Parent Component:


import ChildComponent from "./Child" ;

function ParentComponent(props) {
let [counter, setCounter] = useState(0);

let increment = () => setCounter(++counter);


return (
<div>
<button onClick={increment}>Increment Counter</button>
<ChildComponent counterValue={counter} />
</div>
);
}

As one can see in the code above, we are rendering the child component inside the parent component, by providing a prop called counterValue. Value
of the counter is being passed from the parent to the child component.
We can use the data passed by the parent component in the following way:
function ChildComponent(props) {
return (
<div>
<p>Value of counter: {props.counterValue}</p>
</div>
);
}

We use the props.counterValue to display the data passed on by the parent component.
Child Component to Parent Component (using callbacks)
This one is a bit tricky. We follow the steps below:
 Create a callback in the parent component which takes in the data needed as a parameter.
 Pass this callback as a prop to the child component.
 Send data from the child component using the callback.
We are considering the same example above but in this case, we are going to pass the updated counterValue from child to parent.
Step1 and Step2: Create a callback in the parent component, pass this callback as a prop.
function ParentComponent(props) {
let [counter, setCounter] = useState(0);

let callback = valueFromChild => setCounter(valueFromChild);

return (
<div>
<p>Value of counter: {counter}</p>
<ChildComponent callbackFunc={callback} counterValue={counter} />
</div>
);
}

As one can see in the code above, we created a function called callback which takes in the data received from the child component as a parameter.
Next, we passed the function callback as a prop to the child component.
Step3: Pass data from child to the parent component.
function ChildComponent(props) {
let childCounterValue = props.counterValue;

return (
<div>
<button onClick={() => props.callbackFunc(++childCounterValue)}>
Increment Counter
</button>
</div>
);
}

In the code above, we have used the props.counterValue and set it to a variable called childCounterValue.
Next, on button click, we pass the incremented childCounterValue to the props.callbackFunc.
This way, we can pass data from the child to the parent component.

15. What are Higher Order Components?


Simply put, Higher Order Component(HOC) is a function that takes in a component and returns a new
component.

When do we need a Higher Order Component?


While developing React applications, we might develop components that are quite similar to each other with minute differences.
In most cases, developing similar components might not be an issue but, while developing larger applications we need to keep our code DRY,
therefore, we want an abstraction that allows us to define this logic in a single place and share it across components.
HOC allows us to create that abstraction.
Example of a HOC:
Consider the following components having similar functionality
The following component displays the list of articles:
// "GlobalDataSource" is some global data source
class ArticlesList extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
articles: GlobalDataSource.getArticles(),
};
}

componentDidMount() {
// Listens to the changes added
GlobalDataSource.addChangeListener(this.handleChange);
}

componentWillUnmount() {
// Listens to the changes removed
GlobalDataSource.removeChangeListener( this.handleChange);
}

handleChange() {
// States gets Update whenver data source changes
this.setState({
articles: GlobalDataSource.getArticles(),
});
}

render() {
return (
<div>
{this.state.articles.map((article) => (
<ArticleData article={article} key={article.id} />
))}
</div>
);
}
}

The following component displays the list of users:


// "GlobalDataSource" is some global data source
class UsersList extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
users: GlobalDataSource.getUsers(),
};
}

componentDidMount() {
// Listens to the changes added
GlobalDataSource.addChangeListener(this.handleChange);
}

componentWillUnmount() {
// Listens to the changes removed
GlobalDataSource.removeChangeListener(this.handleChange);
}

handleChange() {
// States gets Update whenver data source changes
this.setState({
users: GlobalDataSource.getUsers(),
});
}

render() {
return (
<div>
{this.state.users.map((user) => (
<UserData user={user} key={user.id} />
))}
</div>
);
}
}
Notice the above components, both have similar functionality but, they are calling different methods to an API endpoint.
Let’s create a Higher Order Component to create an abstraction:
// Higher Order Component which takes a component
// as input and returns another component
// "GlobalDataSource" is some global data source
function HOC(WrappedComponent, selectData) {
return class extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
data: selectData(GlobalDataSource, props),
};
}

componentDidMount() {
// Listens to the changes added
GlobalDataSource.addChangeListener(this.handleChange);
}

componentWillUnmount() {
// Listens to the changes removed
GlobalDataSource.removeChangeListener( this.handleChange);
}

handleChange() {
this.setState({
data: selectData(GlobalDataSource, this.props),
});
}

render() {
// Rendering the wrapped component with the latest data data
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}

We know HOC is a function that takes in a component and returns a component.


In the code above, we have created a function called HOC which returns a component and performs a functionality that can be shared across
both ArticlesList component and UsersList Component.
The second parameter in the HOC function is the function that calls the method on the API endpoint.
We have reduced the duplicated code of the componentDidUpdate and componentDidMount functions.
Using the concept of Higher Order Components, we can now render the ArticlesList and UsersList component in the following way:
const ArticlesListWithHOC = HOC(ArticlesList, (GlobalDataSource) => GlobalDataSource.getArticles());
const UsersListWithHOC = HOC(UsersList, (GlobalDataSource) => GlobalDataSource.getUsers());

Remember, we are not trying to change the functionality of each component, we are trying to share a single functionality across multiple components
using HOC.

16. What is prop drilling in React?

Sometimes while developing React applications, there is a need to pass data from a component that is
higher in the hierarchy to a component that is deeply nested.
To pass data between such components, we pass props from a source component, and keep passing the
prop to the next component in the hierarchy till we reach the deeply nested component.
The disadvantage of using prop drilling is that the components that should otherwise be not aware of
the data have access to the data.

17. What are error boundaries?


Introduced in the version 16 of React, Error boundaries provide a way for us to catch errors that occur in
the render phase.

What is an error boundary?


Any component which uses one of the following lifecycle methods, is considered an error boundary.
In what places can an error boundary detect an error?
Render phase
Inside a lifecycle method
Inside the constructor
Without using error boundaries:
class CounterComponent extends React.Component{
constructor(props){
super(props);
this.state = {
counterValue: 0
}
this.incrementCounter = this.incrementCounter.bind(this);
}

incrementCounter(){
this.setState(prevState => counterValue = prevState+1);
}

render(){
if(this.state.counter === 2){
throw new Error('Crashed');
}

return(
<div>
<button onClick={this.incrementCounter}>Increment Value</button>
<p>Value of counter: {this.state.counterValue}</p>
</div>
)
}
}

In the code above, when the counterValue equals to 2, we throw an error inside the render method.
When we are not using the error boundary, instead of seeing an error, we see a blank page.
Since any error inside the render method, leads to unmounting of the component.
To display an error that occurs inside the render method, we use error boundaries.

With error boundaries:


As mentioned above, error boundary is a component using one or both of the following methods:

static getDerivedStateFromError and componentDidCatch.


Let’s create an error boundary to handle errors in render phase:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToMyService(error, errorInfo);
}

render() {
if (this.state.hasError) {
return <h4>Something went wrong</h4>
}
return this.props.children;
}
}

In the code above, getDerivedStateFromError function renders the fallback UI interface when the render method has an error.
componentDidCatch logs the error information to an error tracking service.
Now with error boundary, we can render the CounterComponent in the following way:
<ErrorBoundary>
<CounterComponent/>
</ErrorBoundary>
1. Differentiate between Real DOM and Virtual DOM.

Real DOM vs Virtual DOM


Real DOM Virtual DOM
1. It updates slow. 1. It updates faster.
2. Can directly update HTML. 2. Can’t directly update HTML.
3. Creates a new DOM if element 3. Updates the JSX if element
updates. updates.
4. DOM manipulation is very 4. DOM manipulation is very
expensive. easy.
5. Too much of memory wastage. 5. No memory wastage.

14. What is Props?


Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always
passed down from the parent to the child components throughout the application. A child component can never send a prop back to the
parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

15. What is a state in React and how is it used?


States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the
objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive
components. They are accessed via this.state().

22. What is an event in React?


In React, events are the triggered reactions to specific actions like mouse hover, mouse click, key press, etc. Handling these events are
similar to handling events in DOM elements. But there are some syntactical differences like:

i. Events are named using camel case instead of just using the lowercase.
ii. Events are passed as functions instead of strings.

The event argument contains a set of properties, which are specific to an event. Each event type contains its own properties and behavior
which can be accessed via its event handler only.

29. What do you know about controlled and uncontrolled components?

Controlled vs Uncontrolled Components


Controlled Components Uncontrolled Components
1. They do not maintain their own state 1. They maintain their own state
2. Data is controlled by the parent component 2. Data is controlled by the DOM
3. They take in the current values through props
3. Refs are used to get their current values
and then notify the changes via callbacks
In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.

Explain Flux.
Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between
multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here
only. Flux provides stability to the application and reduces run-time errors.

36. What is Redux?


Redux is one of the most trending libraries for front-end development in today’s marketplace. It is a predictable state container for JavaScript
applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in
different environments showing consistent behavior.

39. List down the components of Redux.


Redux is composed of the following components:

i. Action – It’s an object that describes what happened.


ii. Reducer – It is a place to determine how the state will change.
iii. Store – State/ Object tree of the entire application is saved in the Store.
iv. View – Simply displays the data provided by the Store.

In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.

46. What is React Router?


React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps
the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for
developing single page web applications. React Router has a simple API.
WebApi
1. Why is the Web API important?
Web API is generally considered as a service that basically provides us information or data from the server. It is very important because of the
following reasons:

 It is used to provide an interface for websites and client applications to have access to data.
 It can also be used to access data from the database and save data back to the database.
 It supports different text formats such as XML, JSON, etc.
 It is suitable or compatible with any type of browser and any type of device like mobile, desktop, web, etc.
 It uses low bandwidth such as XML or JSON data, etc., and is therefore considered good for devices that have limited bandwidth such as
smartphones, etc.
 From a business point of view, web API is more applicable for UI/UX, increases interest in the company’s product and services, increases
website traffic.

2. What is Web API and why we use it ?


Web API (Application Programming Interface), as the name suggests, is an API that can be accessed over the Web using the HTTP protocol. It
is basically considered the best platform for revealing or uncovering data and services to various different services. It is a tool that can be
used to push data to a server and can be accessed by server code. It can be built or developed using various technologies like java, ASP.NET,
etc.

Web API Uses:

 It contains additional layers that simply standardize communications and provide different options on how to format input and output.
 It can be used with ASP.NET MVC and different types of web applications such as ASP.NET WebForms.
 If one wants to create resource-oriented services, then Web API services are considered the best.
 It also helps to develop REST-ful services and SOAP-based services.

3. What are the main return types supported in Web API?


It does not have any specific data type. It can return data of any type depending upon the business requirement. There are many HTTP
methods like GET, POST, PUT, etc., which can return data in different formats depending upon the use case.
4. What is the difference between Web API and WCF?
WCF (Windows Communication Foundation): It is a framework used for developing SOAP (Service-oriented applications). This framework is
used for developing, configuring, and deploying, or implementing network-distributed services.

Web API: It is an application programming interface for both web browsers and web servers. Browser API simply extends or increases the
functionality of web browsers whereas Server API simply extends or increases the functionality of web server.

Web API WCF

It is used to develop both SOAP-based services It is used to deploy only SOAP-based


and RESTful services. services.

It supports various MVC features such as routing,


model binding, etc. It does not support any MVC features.

It supports various protocols such as HTTP,


It only supports HTTP protocol. UDP, custom transport.

It is considered best for developing RESTFUL


services. It supports only limited RESTFUL services.

It is good when one wants to expose an expensive It is good for creating services that uses
range of clients such as iPhones, browsers, mobile expedite transport channels such as TCP,
phones, tablets, etc. UDP, Named pipes, etc.

It offers TEXT, Binary encoding support,


MTOM (Message Transmission Optimization
It offers support for UTF-8 encoding format. Mechanism), etc.

5. Why to choose Web API over WCF?


Web API is considered the best choice over WCF because of the following reasons:

 Web API uses all features of HTTP such as URIs, request/response headers, caching, versioning, various content formats, etc.
 One does not have to define or explain any extra config setting for different devices in Web API.
 Web API uses different text formats including XML because of which it is faster and more preferred for lightweight services.
 Web API also supports MVC features whereas WCF does not support MVC features.
 Web API provides more flexibility as compared to WCF.
 Web API uses standard security like token authentication, basic authentication, etc., to provide secure service whereas WCF uses WS-I
standard to provide secure service.

6. What is different between REST API and RESTful API?


REST (Representation State Transfer) API: It is basically an architectural style that makes productive use
of existing technology and protocols of the web. It is a set of rules that developers need to follow when
they develop their API or services that are scalable. It is used with HTTP protocol using its verbs such as
GET, DELETE, POST, PUT.
RESTful API: It is simply referred to as web services executing such as architecture.

REST API RESTful API

REST is an architectural pattern used for


creating web services. RESTful API is used to implement that pattern.

The data format of REST is based on The data format of RESTful is based on JSON, HTTP, and
HTTP. Text.

Working of URL is based on request


and response. Working of RESTful is based on REST applications.

It is more user-friendly and highly


adaptable to all business enterprises
and IT. It is too flexible.

It simply follows REST infrastructure that provides


It is required to develop APIs that allow interoperability among different systems on the whole
interaction among clients and servers. network.

7. What are the advantages of using Rest in Web API?


REST is very important and beneficial in Web API because of the following reasons:

 It allows less data transfer between client and server.


 It is easy to use and lightweight.
 It provides more flexibility.
 It also handles and controls various types of calls, returning various data formats.
 It is considered best for using it in mobile apps because it makes less data transfer between client and server.
 It uses simple HTTP calls for inter-machine communication rather than using more complex options like CORBA, COM+, SOAP, or RPC.

8. What is REST and SOAP? What is different between them?


REST (Representational State Transfer): It is a new and improved form of web service. It describes the architectural style of networked
systems. It does not require greater bandwidth when requests are sent to the server. It just includes JSON message. For example:

{"city":"Mumbai","state":"Maharashtra"}
SOAP (Simple Object Access Protocol): It is a simple and lightweight protocol that is generally used for exchanging structured and typed
information on the Web. It works mostly with HTTP and RPC (Remote Procedure Call). This protocol is mainly used for B2B applications one
can define a data contract with it. SOAP messages are heavier in content and therefore use greater bandwidth.

For example:

<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:
encodingStyle=" http://www.w3.org/2001/12/soap-encoding">
<soap:Body>
<Demo.guru99WebService xmlns="http://tempuri.org/"> <EmployeeID>int</EmployeeID>
</Demo.guru99WebService>
</soap:Body>
</SOAP-ENV:Envelope>
REST SOAP

It is basically an architectural pattern. It is basically a messaging protocol.

It usually works with various text


formats such as plain text, HTML, JSON,
XML, etc. It only works with XML formats.

It has some specifications for both stateless and


It is totally stateless. stateful implementation.

Its performance is faster as compared to


SOAP. Its performance is slower as compared to REST.

It uses WSDL (Web Service Description Language) for


It uses XML and JSON to send and communication among consumers or users and
receive data. providers.

SOAP includes built-in error handling for


REST has to resend transfer whenever it communications errors using WS-ReliableMessaging
determines any errors. specification.

It calls services by calling RPC (Remote Procedure Call)


It calls services using the URL path. method.

9. What is Web API 2.0?


It is basically an enhanced and modified feature of Web API. This new version supports various new features as given below:

 New Routing Attribute


 Secure ASP.NET Web API using OAuth 2.0
 Support for Cross-Origin requests using CORS
 IHttpActionResult return type
 Support for $expand, $select in OData Service

Because of all the new features of Web API 2.0, it is considered an optimal choice and suitable development model that makes it easier to
develop RESTful services interfaces to different clients running on various platforms. It also supports configuring routes in the Web API
method or controller level.

10. Explain media type formatters.


In web API, media type formatters are classes that are responsible for serialization data. Here, serialization generally means a process of
translating data into a format that can be transmitted and reconstructed later. Because of serializing request/response data, Web API can
understand request data format in a better way and send data in a format that the client expects. It simply specifies data that is being
transferred among client and server in HTTP response or request.

Media Type Formatter Class MIME Type Description

JsonMediaTypeFormatter application/json, text/json Handles JSON format

XmlMediaTypeFormatter application/xml, text/json Handles XML format

application/x-www-form- Handles HTM form URL-


FormUrlEncodedMediaTypeFormatter urlencoded encoded data

application/x-www-form- Handles model-bound HTML


JQueryMvcFormUrlEncodedFormatter urlencoded form URL-encoded data

11. Web API supports which protocol?


Web API generally supports only HTTP protocol.

12. Which of the following Open-source libraries is used by WEB API for
JSON serialization?
Json.NET library is generally used by Web API for JSON serialization.

13. What is XML and JSON?


XML (Extensible Markup Language):

 It is especially designed to store and transport data.


 It is similar to HTML but is more flexible than HTML because it allows users to create their own custom tags.
 It is used for representing structured information such as documents, data, configuration, etc.

JSON (JavaScript Object Notation):

 It is a lightweight format designed to store and transport data.


 It is easier to understand and is a standard text-based format used for representing structured data based on JavaScript object syntax.
 It is faster and easier to use.

14. What are Web API filters?


Filters are basically used to add extra logic at different levels of Web API framework request processing. Different types of Web API filters are
available as given below:

 Authentication Filter: It handles authentication and authenticates HTTP requests. It also helps to authenticate user detail. It checks the
identity of the user.
 Authorization Filter: It handles authorization. It runs before controller action. This filter is used to check whether or not a user is
authenticated. If the user is not authenticated, then it returns an HTTP status code 401 without invoking the action.
 AuthorizeAttribute is a built-in authorization filter provided by Web API.
 Action Filter: It is attributing that one can apply to controller action or entire controller. It is used to add extra logic before or after controller
action executes. It is simply a way to add extra functionality to Web API services.
 Exception Filter: It is used to handle exceptions that are unhandled in Web API. It is used whenever controller actions throw an unhandled
exception that is not HttpResponseException. It will implement an “IExceptionFilter” interface.
 Override Filter: It is used to exclude specific action methods or controllers from the global filter or controller level filter. It is simply used to
modify the behavior of other filters for individual action methods.

15. Who can consume Web API?


A large range of clients such as browsers, mobile devices, iPhone, etc., include or consume web API. It is also good for using along native
applications that require web services but not SOAP support. It can also be consumed by any client that supports HTTP verbs such as GET,
DELETE, POST, PUT.

16. How to handle errors in Web API?


Web API generally provides greater flexibility in terms of handling errors. Exception handling is a technique that is used to handle run-time
errors in application code. One can use HttpResponseException, HttpError, Exception filters, register exception filters, Exception handlers to
handle errors. Exception filter can be used to identify unhandled exceptions on actions or controllers, exception handlers can be used to
identify any type of unhandled exception application-wide, and HttpResponseException can be used when there is the possibility of an
exception.

17. How to register an exception filter globally?


One can register exception filter globally using following code:
GlobalConfiguration.Configuration.Filters.Add (new
MyTestCustomerStore.NotImplExceptionFilterAttribute());

18. What is MVC? Write difference between MVC and Web API?
MVC (Model, View, and Controller) is basically an application design model that comprises three interconnect parts I.e., model, view, and
controller. It allows coders to factor out different components of the application and update them more easily. It is mostly used for
developing model user interfaces. Its main purpose is to display patterns in structure for keeping display and data separate to enable both of
them to change without affecting others.

MVC Web API

It can be used to build Web applications that reply as It is used to build HTTP services that reply
both data and views. only as data.

It returns data in different formats such as


It returns data in JSON format by using JSONResult. JSON, XML, etc.

It does not support content negotiation,


It supports content negotiation, self-hosting. self-hosting.

It is very helpful in creating REST-full


It is not able to build REST-full services. services.

It returns a view (HTML). It returns REST responses.

ASP.NET Web API Interview Questions

19. What is ASP.NET Web API?


ASP stands for Active server pages. ASP.NET is an updated version of legacy ASP. It is a framework that is used for developing HTTP services
to provide responses to client requests. It can be accessed in different applications on different platforms. It is provided by Microsoft open-
source technology for developing and consuming HTTP-based services on top of .NET Framework. It is very easy to build HTTP services using
ASP.NET Web API. These services can be used by different clients as given below:

 Desktop Applications
 Mobile Applications
 IOTs
 Browsers

20. What are the advantages of using ASP.NET Web API?


Some of the core advantages of using ASP.NET Web API are given below:

 It provides the best platform for developing RESTful applications on .NET Framework.
 It works the same way that HTTP works with help of HTTP verbs such as GET, POST, PUT, DELETE for all crud operations.
 It provides enough flexibility in Web API creation.
 It completely supports routing.
 It also supports model binding, validation, Odata (Open Data Protocol) that allows creation and consumption of RESTful APIs.
 It has the ability to develop custom help and test pages with help of ApiExplorer.
 One can develop non-SOAP-based services such as plain XML, JSON strings, etc.
 It also increases the TDD (Test Data-Driven) approach in the development of RESTful services.

21. What are new features used in ASP.NET Web API 2.0
ASP.NET Web API includes a number of new exciting features as given below:

 Attribute Routing
 CORS (Cross-Origin Resource Sharing)
 OWIN (Open Web Interface for .NET) self-hosting
 IHttpActionResult
 Web API OData

22. What is the use of HttpResponseMessage?


It is used to set response values such as header and status control. It simply allows us to work with HTTP protocol. It represents HTTP
response messages that encapsulate data and status code.

// GetEmployee action
public HttpResponseMessage GetEmployee(int id)
{
Employee emp = EmployeeContext.Employees.Where(e => e.Id == id).FirstOrDefault()
;
if (emp != null)
{
return Request.CreateResponse<Employee>(HttpStatusCode.OK, emp);
} else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee
Not Found");
}
}

23. What is the difference between ApiController and Controller?


ApiController: It is used to return data that is arranged in series and then sent to the client.

public class TweetsController : ApiController


{
// GET: /Api/Tweets/
public List<Tweet> Get()
{
return Twitter.GetTweets();
}
}

Controller: It is used to provide normal views.

public class TweetsController : Controller


{
// GET: /Tweets/ [HttpGet] public ActionResult Index()
{
return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
}
}

24. What do you mean by Caching and What are its types?
Caching is basically a technique or process of storing data somewhere or in the cache for future requests. The cache is a temporary storage
area. Caching keeps all frequently or recently accessed files or data in the cache memory and accesses them from the cache itself rather than
actual address of data or files. The cache interface simply improves the storage mechanism for request/response object pairs that are being
cached.

Advantages of Caching:

 It is considered the best solution to ensure that data is served where it is needed to be served that too at a high level of efficiency which is
best for both client and server.
 It delivers web objects faster to the end-user.
 It reduces load time on the website server.
 It leads to faster execution of any process.
 It decreases network costs.

Types of Caching:
There are basically three types of caching as given below:

 Page Caching
 Data Caching
 Fragment Caching

25. WCF is replaced by ASP.NET Web API. True/False?


WCF: It is a framework used for developing SOAP (Service Oriented Applications Protocols). It also supports various transport protocols as
given above.
ASP.NET Web API: It is a framework used for developing non-SOAP-based services. It is limited to HTTP-based services.

No, it's not true that ASP.NET Web API has replaced WCF. WCF was generally developed to develop SOAP-based services. ASP.NET Web API
is a new way to develop non-SOAP-based services such as XML, JSON, etc. WCF is still considered a better choice if one has their service
using HTTP as the transport and they want to move to some other transport like TCP, NetTCP, MSMQ, etc. WCF also allows one-way
communication or duplex communication.

26. What are the main return types supported in ASP. Net Web API?
It supports the following return types:

 HttpResponseMessage
 IHttpActionResult
 Void
 Other types such as string, int, etc.

27. What is ASP.NET Web API routing?


Routing is the most important part of ASP.NET Web API. Routing is a way how Web API matches a URI to an action. It is basically a process
that decides which action and controller should be called. The controller is basically a class that handles all HTTP requests. All public methods
of controllers are basically known as action methods or just actions. Whenever a Web API framework receives any type of request, it routes
that request to action.
There are basically two ways to implement routing in Web API as given below:
Convention-based routing: Web API supports convention-based routing. In this type of routing, Web API uses route templates to select
which controller and action method to execute.

Attribute-based routing: Web API 2 generally supports a new type of routing known as attribute routing. As the name suggests, it uses
attributes to define routes. It is the ability to add routes to the route table via attributes.

28. HOW to secure ASP.NET Web API?


Web API has become key to programming web-based interactions. It can be accessed by anyone who knows the URL. Therefore, they have
become targets for hackers. One needs to secure Web API by controlling Web API and by deciding who can and who cannot have access to
Web API. There are basically two ways or techniques that make our Web API more secure.

Authentication: It is a process that helps to identify and check users by their credentials such as password, username, etc. To have access to
the web API, firstly user credentials are needed to be passed in the request header. If user credentials are not passed into the request header,
then the server returns 401 status code (unauthorized). The best authentication to be used is OAuth 2.0.

Authorization: It is a process that helps to decide whether or not a user has access to perform an action. Authorization filters are used to
implement authorization.

29. What are Exception filters in ASP.NET Web API?


Exception filter is generally used to handle all unhandled exceptions that are generated in web API. It implements IExceptionFilters interface.
It is the easiest and most flexible to implement. This filter is executed whenever the controller method throws any unhandled exception at any
stage that is not an HttpResponseExecption exception.

30. Which .NET framework supports ASP.NET Web API?


.NET Framework 4.0 generally supports the first version of ASP.NET Web API. After that, .NET Framework 4.5 supports the latest version of
web API i.e., ASP.NET Web API 2.

31. What is HttpConfiguration in Web API?


It is considered as the main class that includes different properties with help of which one can override the default behavior of Web API.

Some properties are given below:

 DependencyResolver: It sets or gets a dependency resolver for dependency injection.


 Services: It gets web API services.
 ParameterBindingRules: It gets a collection of rules for how parameters should be bound.
 MessageHandlers: It sets or gets message handlers.
 Formatters: It sets or gets media-type formatters.

32. Can we return View from ASP.NET Web API method?


No, we cannot return the view from the ASP.NET Web API method. ASP.NET web API develops HTTP services that provide raw data or
information. ApiController in ASP.NET MVC application only renders data that is serialized and sent to the client. One can use a controller to
provide normal views.

33. What is content negotiation in ASP.Net Web API?


Content negotiation is basically a process of selecting the best representation from multiple representations that are available for a given
response. It simply allows one to choose rather than negotiate content that one wants to get in response. It is performed at the server-side. In
simple words, it chooses the best media type for matters to return a response to an incoming request.

34. Difference between HTTP GET vs HTTP Post?


HTTP (HyperText Transfer Protocol) simply manages request-response between client and server. It works as a request-response protocol
between client and server.

HTTP GET: This method is used to get information or data from a respective server at a specified URL.

Example:
GET/RegisterStudent.asp?user=value1&pass=value2

HTTP POST: This method is used to send data or information to respective servers.

Example:
POST/RegisterStudent.asp HTTP/1.1
Host: www.guru99.com
user=value1&pass=value2

HTTP GET HTTP POST

Its parameters are included in the


URL. Its parameters are included in the body.

This method is used to request data


from specified resources and has no This method is used to send data to a server to create or
other effect. update resources.

It carries request parameters in the message body that


It carries a request parameter make it a more secure way of sending data or information
appended in the URL string. from the client to the server.

Request method using GET is


cacheable. Request method using POST is not cacheable.

GET requests are less safe than POST. Post request is safer than GET.

There is a restriction on data type in


GET method and only ASCII There are no restrictions on data type in this method and
characters are allowed. binary data is also allowed.

Data is not displayed in the URL. It is present in the


Data is visible to everyone in the URL. payload.

35. What is CORS in Web API?


CORS (Cross-Origin Resource Sharing) is basically a mechanism that allows one to make requests from one website to another website in a
browser that is normally not allowed by another policy called SOP (Same Origin Policy). It supports secure cross-origin requests and data
transfers among clients or browsers and servers. Here, cross-origin request means requests coming from different origins. CORS simply
resolves the same-origin restriction for JavaScript. One can enable CORS for web API using the respective web API package or OWIN
middleware.

36. Name method that validates all controls on page?


Page.Validate()

37. What parameters can be passed in the URL of API?


Context keys, documents keys, or anything that initiates API to hit the exact end-point are few parameters that one can pass in the URL to
define the complete end-point.

38. What is the use of DelegatingHandler?


DelegatingHandler is used to develop a custom Server-Side HTTP Message Handler in ASP.NET Web API. It is used to represent Message
Handlers before routing in Web API.

39. Web API uses which library for JSON serialization?


Json.NET library is used by Web API for JSON serialization.

40. Explain method to handle error using HttpError in Web API?


CreateErrorResponse is an extension method that can be used in Web API controller methods to return error codes and error messages. It
creates an HttpError object and then wraps it inside an HttpResponseMessage object.

41. How to unit test Web API?


Using Web API tools like Fiddler, we can perform unit testing in Web API. Fiddler is basically a free debugging proxy for any browser that can
be used to compose and execute various HTTP requests to Web API and check HTTP response. It is simply used for testing restful web
services. It allows one to inspect and check both incoming and outgoing data to monitor and modify requests and responses before the
browser receives them. Below is given some setting that is needed to be done fiddler:

Fiddler – Compose Tab -> Enter Request Headers -> Enter Request Body and then execute.

Conclusion

42. Conclusion
Web API is an extensible framework that serves us information from the server and is used for developing ASP.NET. It is totally based on Http
and is easy to define, expose and consume in a REST-ful way. It is considered an ideal platform for developing RESTful applications on .NET
framework. From the above Web API interview questions and answers, you can learn more about Web API, its importance, its benefits, etc.
1) What is Web API?

WebAPI is a framework which helps you to build/develop HTTP services

4) Is it right that ASP.NET Web API has replaced WCF?Software Testing

It's a not at all true that ASP.NET Web API has replaced WCF. In fact, it is another way of building non-SOAP based
services, i.e., plain XML or JSON string.

6) What are main return types supported in Web API?

A Web API controller action can return following values:

 Void – It will return empty content


 HttpResponseMessage - It will convert the response to an HTTP message.
 IHttpActionResult - internally calls ExecuteAsync to create an HttpResponseMessage
 Other types - You can write the serialized return value into the response body

7) Web API supports which protocol?

Web App supports HTTP protocol.

8) Which .NET framework supports Web API?

NET 4.0 and above version supports web API.

9) Web API uses which of the following open-source library for JSON serialization?

Web API uses Json.NET library for JSON serialization.

10) By default, Web API sends HTTP response with which of the following status code for all uncaught exception?

500 - Internal Server Error

11) What is the biggest disadvantage of "Other Return Types" in Web API?

The biggest disadvantage of this approach is that you cannot directly return an error code like 404 error.

12) How do you construct HtmlResponseMessage?

Following is the way to construct to do so,

public class TestController : ApiController


{

public HttpResponseMessage Get()

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");

response.Content = new StringContent("Testing", Encoding.Unicode);

response.Headers.CacheControl = new CacheControlHeaderValue()

MaxAge = TimeSpan.FromMinutes(20)

};

return response;

13) What is Web API Routing?

Routing is pattern matching like in MVC.

All routes are registered in Route Tables.

For example:

Routes.MapHttpRoute(

Name: "ExampleWebAPIRoute",

routeTemplate: “api/{controller}/{id}

defaults: new { id = RouteParameter.Optional}

14) What is SOAP?

SOAP is an XML message format used in web service interactions. It allows to send messages over HTTP or JMS, but other
transport protocols can be used. It is also an XML-based messaging protocol for exchanging information among computers.

15) What is the benefit of using REST in Web API?

REST is used to make fewer data transfers between client and server which make it an ideal for using it in mobile apps.
Web API also supports HTTP protocol. Therefore, it reintroduces the traditional way of the HTTP verbs for communication.

16) How can we use Web API with ASP.NET Web Form?

Web API can be used with ASP.NET Web Form


It can be performed in three simple steps:

1. Create a Web API Controller,


2. Add a routing table to Application_Start method of Global.sax
3. Then you need to make a jQuery AJAX Call to Web API method and get data.

17) How to you can limit Access to Web API to Specific HTTP Verb?

Attribute programming plays a important role. It is easy to restrict access to an ASP.NET Web API method to be called using
a particular HTTP method.

18) Can you use Web API with ASP.NET Web Form?

Yes, It is possible to use Web API with ASP.Net web form. As it is bundled with ASP.NET MVC framework. However, it can
be used with ASP.NET Web Form.

19) How Can assign alias name for ASP.NET Web API Action?

We can give alias name for Web API action same as in case of ASP.NET MVC by using "ActionName" attribute as follows:

[HttpPost]

[ActionName("SaveStudentInfo")]

public void UpdateStudent(Student aStudent)


{
StudentRepository.AddStudent(aStudent);
}

20) What is the meaning of TestApi?

TestApi is a utility library of APIs. Using this library tester developer can create testing tools and automated tests for a .NET
application using data-structure and algorithms.

21) Explain exception filters?

It will be executed when exceptions are unhandled and thrown from a controller method. The reason for the exception can
be anything. Exception filters will implement "IExceptionFilter" interface.

22) How can we register exception filter from the action?

We can register exception filter from action using following code:

[NotImplExceptionFilter]

public TestCustomer GetMyTestCustomer(int custid)

//write the code

23) How you can return View from ASP.NET Web API method?
No, we can't return a view from ASP.NET Web API Method. Web API creates HTTP services that render raw data. However,
it's also possible in ASP.NET MVC application.

24) How to register exception filter globally?

It is possible to register exception filter globally using following code-

GlobalConfiguration.Configuration.Filters.Add(new

MyTestCustomerStore.NotImplExceptionFilterAttribute());

25) Explain what is REST and RESTFUL?

REST represents REpresentational State Transfer; it is entirely a new aspect of writing a web app.

RESTFUL: It is term written by applying REST architectural concepts is called RESTful services. It focuses on system
resources and how the state of the resource should be transported over HTTP protocol.

26) Give me one example of Web API Routing?

Config.Routes.MapHttpRoute(

name: "MyRoute,"//route name

routeTemplate: "api/{controller}/{action}/{id}",//as you can see "API" is at the begi


nning.

defaults: new { id = RouteParameter.Optional }

);

27) How can you handle errors in Web API?

Several classes are available in Web API to handle errors. They are HttpError, Exception Filters, HttpResponseException,
and Registering Exception Filters.

28) What New Features comes with ASP.NET Web API 2.0?

The latest features of ASP.NET Web API framework v2.0 are as follows:

 Attribute Routing
 Cross-Origin Resource Sharing
 External Authentication
 Open Web Interface NET
 HttpActionResult
 Web API OData

29) How can you restrict access methods to specific HTTP verbs in Web API?

With the help of Attributes (like HTTP verbs), It is possible to implement access restrictions in Web API.

It is possible to define HTTP verbs as an attribute to restrict access. Example:

[HttpPost]
public void Method1(Class obj)

//logic

30) How can you pass multiple complex types in Web API?

Two methods to pass the complex types in Web API –

Using ArrayList and Newtonsoft array

31) Write a code for passing ArrayList in Web API?

ArrayList paramList = new ArrayList();

Category c = new Category { CategoryId = 1, CategoryName =“MobilePhones”};

Product p = new Product { Productcode = 1, Name = “MotoG”, Price = 15500, CategoryID


= 1 };

paramList.Add(c);

paramList.Add(p);

32) Name the tools or API for developing or testing web api?

Testing tools for web services for REST APIs include:

1. Jersey API
2. CFX
3. Axis
4. Restlet

33) What is REST?

REST is architectural style. It has defined guidelines for creating services which are scalable. REST used with HTTP
protocol using its verbs GET, PUT, POST and DELETE.

34) How to unit test Web API?

We can perform a Unit test using Web API tools like Fiddler.

Here, are some setting to be done if you are using

Fiddler –Compose Tab -> Enter Request Headers -> Enter the Request Body and execute

35) How can we restrict access to methods with specific HTTP verbs in Web API?

Attribute programming is widely used for this functionality. Web API also allows restricting access of calling methods with the
help of specific HTTP verbs. It is also possible to define HTTP verbs as attribute over method.

36) What is the usage of DelegatingHandler?


DelegatingHandler is used in the Web API to represent Message Handlers before routing.

37) How can we register exception filter from the action?

We can register exception filter from action using following code

[NotImplExceptionFilter]

public TestCust GetMyTestCust (int custno)

//write the code

38) Tell me the code snippet to show how we can return 404 errors from HttpError?

Code for returning 404 error from HttpError

string message = string.Format(“TestCustomer id = {0} not found”, customerid);

return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);

39) Explain code snippet to register exception filters from controller?

[NotImplExceptionFilter]

public class TestCustController : Controller

//Your code goes here

40) Web API supports which protocol?

Web App support HTTP protocol

41) Which of the following .NET framework supports Web API?

Web API is supported by NET 4.0 version

42) Web API uses which library for JSON serialization?

Web API uses Json.NET library for JSON serialization.

43) By default, Web API sends HTTP response with which of the following status code for all uncaught exception?

500 - Internal Server Error

44) Explain method to handle error using HttpError in Web API?


In WEB API HttpError used to throw the error info in the response body. “CreateErrorResponse” method is can also use
along with this, which is an extension method defined in “HttpRequestMessageExtension.”

45) How can we register exception filter globally?

We can register exception filter globally using following code:

GlobalConfiguration.Configuration.Filters.Add (new MyTestCustomerStore.NotImplExcepti


onFilterAttribute());

46) How to handle errors in Web API?

Several classes are available in Web API to handle errors. They are HttpError, HttpResponseException, Exception Filters,
Registering Exception Filters.

47) What is the benefit of WebAPI over WCF?

WCF services use the SOAP protocol while HTTP never use SOAP protocol. That’s why WebAPI services are lightweight
since SOAP is not used. It also reduces the data which is transferred to resume service. Moreover, it never needs too much
configuration. Therefore, the client can interact with the service by using the HTTP verbs.

48) State differences between MVC and WebAPI

MVC framework is used for developing applications which have User Interface. For that, views can be used for building a
user interface.

WebAPI is used for developing HTTP services. Other apps can also be called the WebAPI methods to fetch that data.

49) Who can consume WebAPI?

WebAPI can be consumed by any client which supports HTTP verbs such as GET, PUT, DELETE, POST. As WebAPI
services don’t need any configuration, they are very easy to consume by any client. Infract, even portable devices like
Mobile devices can easily consume WebAPI which is certainly the biggest advantages of this technology.

50) How can we make sure that Web API returns JSON data only?

To make Web API serialize the returning object to JSON format and returns JSON data only. For that you should add the
following code in WebApiConfig.cs class in any MVC Web API Project:

//JsonFormatter

//MediaTypeHeaderValue

Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("app
lication/json"));

//JsonFormatter

//MediaTypeHeaderValue
Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("app
lication/json"))

JQuery
1. What is jQuery?

jQuery is a open source and most popular library for simiplifying interactions between DOM and
JavaScript.

2. What are the advantages of jQuery?

 Most popular and open source


 Very fast and easily extensible
 Used to develop cross browser compatible web applications as jQuery works in almost the same
manner for different kinds of browsers.
 Improves the performance of an application when using the minimised version of the jQuery
library. The size of the minimized js file is almost 50% less than the normal js file. Reduction in
the file size makes the web page load and work faster.
 Commonly implemented UI related functionalities are written using minimal lines of codes

3. Is jQuery a JavaScript or JSON library file?

jQuery is said to be a library of single JavaScript file which consists of DOM/CSS manipulations, event
effects or animations, AJAX functions and various commonly used plugins.

4. Does jQuery work for both HTML and XML documents?

No. jQuery works only for HTML documents.

5. What are the jQuery functions used to provide effects?


Some of methods are listed below which provides the effect:
1. toggle() :
 This function is used to check the visibility of selected elements to toggle between hide() and show() for the selected elements
where:
o show() is run when the element is hidden.
o hide() is run when the element is visible.
 Syntax: $(selector).toggle(speed, easing, callback)
2. slideDown() :
 This function is used to either check the visibility of selected elements or to show the hidden elements. We can use this function
on the following types of hidden elements:
o Elements that are hidden using jQuery methods.
o Elements that are hidden using display: none in the element’s CSS properties.
 Syntax: $(selector).slideDown( speed, easing, callback )
3. fadeOut():
 This function is used to change the level of opacity for element of choice from visible to hidden. When used, the fadded
element will not occupy any space in DOM.
 Syntax: $(selector).fadeOut( speed, easing, callback )
4. fadeToggle():
 This is used for toggling between the fadeIn() and fadeOut() methods.
o If elements are faded in state, fadeToggle() will fade out those elements.
o If elements are faded out, fadeToggle() will fade in those elements.
 Syntax: $(selector).fadeToggle(speed, easing, callback)
5. animate():
 The method performs custom animation of a set of CSS properties. This method changes an element from one state to another
with CSS styles.
 The CSS property value is changed gradually, to create an animated effect.
 Syntax: (selector).animate({styles},speed,easing,callback) where “styles” is a required field that specifies one or more CSS
properties/values to animate. The properties needs to be mentioned in camel casing style.
 The parameters “speed”, “easing” and “callback” in the syntaxes of the above methods represent:
o speed: Optional parameter and used for specifying the speed of the effect. The default value is 400 millisecond. The
possible value of speed are “slow”, “fast” or some number in milliseconds.
o easing: Again optional parameter which is used for specifying the speed of element to different types of animation.
The default value is “swing”. The possible value of easing are “swing” and “linear”.
o callback: Optional parameter. The callback function specified here is executed after the effect method is
completed.
6. What is the use of css() method in jQuery?

The css() method is used to change style property of the selected element.

7. What are events in jQuery?

User actions on a webpage are called events and handling responses to those is called event
handling. jQuery provides simple methods for attaching event handlers to selected elements.
When an event occurs, the provided function is executed.

8. What is the significance of jQuery.length?

jQuery.length property is used to count number of the elements of the jQuery object.

9. What is jQuery click event?

 jQuery click event happens when we click on an HTML element.


 jQuery provides a method click() method that aids to trigger the click event.
 For example $(“p”).click() will trigger the click event whenever the elements with paragraph tag is clicked on a browser page.
 Syntax:
$(selector).click(function(){
//code that runs when the click event is triggered
});

10. Can you tell something about jQuery each() method?

 The each() method in jQuery allows us to loop through different datasets such as arrays or objects (even DOM objects).
 It can be used to loop through a number of DOM objects from the same selectors.
 For example, if you want to add a width=“600” to all the images in a page then we select all images and loop through each of them and
add width = "600" to each tag. We can write the code as below:
$("img").each(function(im){
$(this).attr("width","600")
});

 $ is a jQuery object definer. In the above syntax, “this” is a DOM object and we can apply jQuery functions to only jQuery objects which is
why we convert the DOM object to jQuery object by wrapping it inside the $ definer.
 We can also use each() to loop through the arrays of data and get the index and the value of the position of data inside the array.
 For example,
var list = ["InterviewBit", "jQuery", "Questions"];
$.each(list, function(index, value){
console.log(index + " "+ value);
})

 The above code prints

0 InterviewBit
1 jQuery
2 Questions
 You can also use each() to loop through objects.
 For example:
var obj = {"name":"InterviewBit","type": "jQuery"};
$.each(obj, function(key,value){
console.log(key + " - " + value);
})

 The above code prints:

name - InterviewBit
type - jQuery
11. What is the difference between javascript and jquery?

 JavaScript is an interpreted language written in C and is combination of ECMAScript and DOM where jQuery is a JavaScript library
developed to run things faster and make things simplified for JavaScript. jQuery doesnt have the ECMAScript.
 JavaScript requires long lines of code to code a functionality where in case of jQuery, just import the library and call the functions which
would reduce the programmer’s effort of coding.
 JavaScript doesnt have the cross browser compatible functionality which is why a developer has to write code manually to implement the
functionality. Whereas the cross browser code compatibility is inbuilt in jQuery.
12. What are the selectors in jQuery? How many types of selectors in jQuery?
In order to work with any element on the web page, we would first need to find it. Selectors find the HTML elements in jQuery. Some of the most
commonly used and basic selectors are:
 Name: Used to select all elements which matches the given element Name.
 #ID: Used to select a single element which matches with the given ID
 .Class: Used to select all elements which match with the given Class.
 Universal (*): Used to select all elements available in a DOM.
 Multiple Elements E, F, G: Used to selects the combined results of all the specified selectors E, F or G.
 Attribute Selector: Used to select elements based on its attribute value.
13. Explain how CSS classes can be manipulated in HTML using jQuery.

 Query provides several methods to manipulate the CSS classes assigned to HTML elements. The most important methods are addClass(),
removeClass() and toggleClass().
 addClass(): This method adds one or more classes to the selected elements.
o Syntax: $(selector).addClass(className);
o You can also add multiple classes to the selector. Syntax:$(selector).addClass(class1, class2);
 removeClass(): Similar to adding class, you can also remove the classes from the elements by using this method.
o The removeClass() method can remove a single class, multiple classes, or all classes at once from the selected elements.
o Syntax:
 For removing one class: $(selector).removeClass(class1);
 For removing multiple class: $(selector).removeClass(class1, class2, class 3);
 For removing all classes at once: $(selector).removeClass()
 toggleClass(): This method is used for adding or removing one or more classes from the selected elements in such a way that if the
selected element already has the class, then it is removed. Else if an element does not have the specified class, then it is added i.e.
it toggles the application of classes.
o Syntax: $(selector).toggleClass(className);
14. How to perform jQuery AJAX requests?

 jQuery provides the ajax() method to perform an AJAX (asynchronous HTTP) request.
 Syntax: $.ajax({name:value, name:value, ... }). The parameters specify one or more value of name-value pairs.
o url : this name specifies the URL to send the request to. Default is the current page.
o success(result,status,xhr) : success callback function which runs when the request succeeds
o error(xhr,status,error) : A function to run if the request fails.
o async : Boolean value that indicates whether the request should be handled asynchronous or not. Default value is true.
o complete(xhr,status) : A function to run when the request is completed (after success and error functions are handled)
o xhr : A function used for creating the XMLHttpRequest object
 Example:
$.ajax({
url: "resourceURL",
async: false,
success: function(result){
$("div").html(result);
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});

15. What does the following code do?

$( "div#firstDiv, div.firstDiv, ol#items > [name$='firstDiv']" )

 The given code is an example of getting elements that satisfy multiple selectors at once. The function returns a jQuery object having the
results of the query.
 The given code does a query to retrieve those <div> element with the id value firstDiv along with all <div> elements that has the class
value firstDiv and all elements that are children of the <ol id="items"> element and whose name attribute ends with the string firstDiv.
16. Consider the following code that exists in following HTML with the CSS:

<div id="expand"></div>

<style>
div#expand{
width: 50px;
height: 50px;
background-color: gray;
}
</style>

 Write jQuery code to animate the #expand div, expanding it from 50 * 50 pixels to 300 * 300 pixels within five seconds.
 We can do this by using the animate() function. We first need to have access to the div element which has id value of expand and then
apply animate function on the element as follows:
$("#expand").animate(
{
width: "300px",
height: "300px",
},
5000
);

17. What does the following code do?

$( "div" ).css( "width" , "500px" )


.add( "p" )
.css( "background-color", "yellow" );

 The given code first selects all the <div> elements and applies width of 500px to them and adds all the <p> elements to the elements
selection after which the code can finally change the background color to yellow for all the <div> and <p> elements
 The given code is an example of method chaining in jQuery which is used to accomplish a couple of things in one single instruction.
18. Can you explain the difference between jQuery.get() and jQuery.ajax()?

 jQuery.ajax() allows the creation of highly-customized AJAX requests, with options for how long to wait for a response, what to do once the
request is successful, how to handle a failure scenarios, whether the request to be sent is blocking (synchronous) or non-blocking
(asynchronous), what format to expect as the response, and many more customizable options.
 jQuery.get() is uses jQuery.ajax() underneath to create an AJAX request typically meant for simple retrieval of information.
o There are various other pre-built AJAX requests given by jQuery such as:
 jQuery.post() for performing post requests
 jQuery.getScript() meant for loading and then executing a JavaScript file from the server using GET request.
 jQuery.getJSON() for loading JSON-encoded data from the server using a GET HTTP request.
19. Which of the two lines of code below is more efficient and
why? document.getElementById("interviewBit"); OR $("#interviewBit");

 The code document.getElementById( "interviewBit" ); is more efficient because its the pure JavaScript version.
 The reason being jQuery is built on top of JavaScript and internally uses its methods to make DOM manipulation easier. This introduces
some performance overhead. We need to remember that jQuery is not always better than pure JavaScript and we need to use it only if it
adds advantage to our project.
20. Can you write a jQuery code selector that needs to be used for querying all elements whose ID ends
with string “IB”?

We can use the following selector: $("[id$='IB']")

21. Explain the .promise() method in jQuery.

 The .promise() method returns a dynamically generated promise that is resolved when all actions of a certain type bound to the collection,
queued or not, have ended.
 The method takes two optional arguments:
o type - The default type is “fx” which indicates that the returned promise is resolved only when all animations of the selected
elements have been completed.
o target - If a target object is specified, .promise() will attach to promise to that specified object and then return it rather than
creating a new one.
22. Consider the below code snippet and assume that there are 5 <div> elements on the page. What is
the difference between the start and end times displayed?

function getMinsSeconds() {
var dt = new Date();
return dt.getMinutes()+":"+dt.getSeconds();
}

$( "input" ).on( "click", function() {


$( "p" ).append( "Start: " + getMinsSeconds() + "<br />" );
$( "div" ).each(function( i ) {
$( this ).fadeOut( 1000 * ( i * 2 ) );
});
$( "div" ).promise().done(function() {
$( "p" ).append( "End: " + getMinsSeconds() + "<br />" );
});
});

 For the above code, the difference between the start and end times will be 10 seconds.
 This is because .promise() will wait for all <div> animations (here, all fadeOut() calls) to complete, the last one will complete 10 seconds
(i.e. 5 * 2 = 10 seconds) after the fadeOut() starts.
23. Can you tell the difference between prop() and attr()s?

 Both prop() and attr() can be used to get or set the value of the specified property of an element attribute.
 The attr() gives the default value of a property whereas prop() returns its current value.
MicroService
Download PDF

1) Explain microservices architecture

Microservice Architecture is an architectural development style which builds an application as a collection of small
autonomous services developed for a business domain.

2) Name three commonly used tools for Microservices

 Wiremock, 2.) Docker and 3.) Hysrix are important Microservices tool.

3) What is Monolithic Architecture? Monolithic architecture is like a big container in which all the software components of
an application are clubbed inside a single package.

4) What are the advantages of microservices?

Here, are some significant advantages of using Microservices:

 Technology diversity, e., Microservices can mix easily with other frameworks, libraries, and databases
 Fault isolation, e., a process failure should not bring the whole system down.
 Greater support for smaller and parallel team
 Independent deployment
 Deployment time reduce

5) What is Spring Cloud?

Spring cloud is an Integration software that integrates with external systems. It allows microservices framework to build
applications which perform restricted amounts of data processing.
6) Discuss uses of reports and dashboards in the environment of Microservices

Reports and dashboards help in monitoring and upkeep of Microservices. Tons of Application Monitoring Tools assist in this.

7) What are main differences between Microservices and Monolithic Architecture?

Microservices Monolithic Architecture

Service Startup is fast Service startup takes time

Microservices are loosely coupled architecture. Monolithic architecture is mostly tightly


coupled.

Changes done in a single data model does not affect Any changes in the data model affect the
other Microservices. entire database

Microservices focuses on products, not projects Monolithic put emphasize over the whole
project

8) What are the challenges faced while using Microservices?

 Microservices always rely on each other. Therefore, they need to communicate with each other.
 As it is distributed system, it is a heavily involved model.
 If you are using Microservice architecture, you need to ready for operations overhead.
 You need skilled professionals to support heterogeneously distributed microservices.

9) In which cases microservice architecture best suited?

Microservice architecture is best suited for desktop, web, mobile devices, Smart TVs, Wearable, etc.

10) Tell me the name of some famous companies which are using Microservice architecture

Most large-scale websites like Twitter, Netflix, Amazon, have advanced from a monolithic architecture to a microservices
architecture.
11) What are the characteristics of Microservices?

 Essential messaging frameworks


 Decentralized Governance
 Easy Infrastructure automation
 Design for failure
 Infrastructure automation

12) What is RESTful?

Representational State Transfer (REST)/RESTful web services is an architectural style that helps computer systems to
communicate over the internet. These web services make microservices easier to understand and implement.

13) Explain three types of Tests for Microservices? In Microservice architecture tests are divided into three broad
categories:

 At the bottom level test, we can perform a general test like performance and unit tests. These kinds of tests are
entirely automated.
 At the middle level, we can perform exploratory tests like the stress tests and usability tests.
 At the top level, we can conduct acceptance tests which are mostly fewer in numbers. It also helps stakeholders to
know about different software features.

14) What are Client certificates?

Client certificates is a digital certificate used to make authenticated requests to a remote server. It is termed as a client
certificate.

15) Explain the use of PACT in Microservices architecture?

It is an open source tool which allows testing interactions between service providers and consumers. However, it is
separated from the contract made. This increases the reliability of the Microservices applications.

16) What is the meaning of OAuth?

OAuth means open authorization protocol. This protocol allows you to access the client applications on HTTP for third-party
providers GitHub, Facebook, etc. It helps you to share resources stored on one site with another site without the need for
their credentials.

17) What is End to End Microservices Testing?

End-to-end testing validates every process in the workflow is functioning correctly. It also ensures that the system works
together as a whole and satisfies all requirements.

18) Why are Container used in Microservices?

Containers are easiest and effective method to manage the microservice based application. It also helps you to develop and
deploy individually. Docker also allows you to encapsulate your microservice in a container image along with its
dependencies. Microservice can use these elements without additional efforts.

19) What is the meaning of Semantic monitoring in Microservices architecture?

Semantic monitoring combines automated tests with monitoring of the application. It allows you to find out reasons why your
business is not getting more profits.

20) What is a CDC?


CDC is Consumer-Driven Contract. It is a pattern for developing Microservices so that external systems can use them.

21) What is the use of Docker?

Docker offers a container environment which can be used to host any application. This software application and the
dependencies that support it which are tightly-packaged together.

22) What are Reactive Extensions in Microservices?

Reactive Extensions is also called Rx. It is a design pattern which allows collecting results by calling multiple services and
then compile a combined response. Rx is a popular tool in distributed systems which works exactly opposite to legacy flows.

23) Explain the term 'Continuous Monitoring.'

Continuous monitoring is a method which is used for searching compliance and risk issues associated with a company’s
operational and financial environment. It contains human, processes, and working systems which support efficient and
actual operations.

24) How independent micro-services communicate with each other?

It depends upon your project needs. However, in most cases, developers use HTTP/REST with JSON or Binary protocol.
However, they can use any communication protocol.

You might also like