You are on page 1of 28

Learning and Knowledge Management

ReactJS

Introduction to axios
(http client)
Ground Rules
For a successful class, please:
• Arrive on time.
• Turn off cell phones.
• Assist your colleagues; show respect to all individuals regardless of their skill and
knowledge level.
• Do not use class time to surf the net, check e-mail, or use instant messaging.
• Adhere to attendance policy as directed by your local training coordinator.
• Make the most of face-to-face training; ask questions and share your own insights and
expertise.
• Leave the room only during break times or in the event of an emergency.
• Manage expectations for your other responsibilities.

2
Agenda
1 Introduction http client

2 REST API

3 Introduction to axios

4 Parameters

5 Get Request

6 Post Request

7 Demo

8 Activity

3
Introduction to HTTP
HTTP is a asymmetric request-response client-server Protocol

Connection Oriented

Stateless

Extensible

Data will be transmitted over the network

Works on Application Layer

4
Introduction to HTTP Continued….
1. Client request the Url from Browser

(https://https://mylearning.accenture.co
3. Request Object
m/)
Processed on Server
2. Request Object
GET URL HTTP1.1
HOST: Host port

4. Response Object
HTTP1.1 200 OK
5. Client Formats the Response and <html></html>
Render 3

5
Introduction to HTTP
• REST - based on REpresentational State Transfer

• Introduced and defined in 2000 by Roy Fielding

• used in designing the HTTP 1.1 and Uniform Resource Identifiers (URI) standards

• Available Operations are

• GET

• HEAD

• POST

• PUT

• PATCH

• DELETE

• CONNECT

• OPTIONS

• TRACE
3

• RESTful systems aim for fast performance, reliability, and reusing components without affecting running System.

6
Architectural properties

The constraints of the REST architectural style affect the following architectural properties

• performance
• scalability
• simplicity of a uniform interface.
• Modification as per Requirement
• visibility of communication between components by service agents;
• portability of components by moving program code with the data;
• reliability in the resistance to failure at the

7
Architecture Constraints

Six REST architectural constraints:

• Use of a uniform interface (UI


• Client-server based
• Stateless operations
• RESTful resource caching
• Layered system
• Code on demand

8
Introduction to HTTP Client - AXIOS

The request is made by bowser or Http clients to server using some of the methods like
get, post, put etc

The most commonly used methods are get and post. Get method is considered as safe
because it is used only to retrieve the data

AXIOS is one of the Http client which uses different request methods to make a request to
server

Promise based HTTP client for the browser

In this module we will see how axios can be used to make http request.
3

9
Axios Features

• Make XMLHttpRequests from the browser

• Make http requests

• Supports the Promise API

• Intercept request and response

• Transform request and response data

• Cancel requests

• Automatic transforms for JSON data

10
Introduction to HTTP Client – AXIOS (cont…)

The first step is to install axios using npm

npm install axios - -save-dev

11
Demo – AXIOS – Explanation(Cont…)

Get method is invoked using axios(Http client). Get method require url . In this example we are
using JSONPlaceholder which is fake REST API for testing and prototyping only.

As mentioned Axios is promise based Http client, which will be resolved on successful
completion of the request, otherwise the request will be rejected

“then” section will be executed on successful completion of the request. The response will be
properly formatted in json and displayed on the console

“catch” section will be executed if the request is rejected and error message is displayed on
the console

12
Demo – AXIOS – Explanation

Calling of an API for processing


api.get("/courses.json")

.then((response) => { This API holds data in json format


this.setState({ which will be requested by axios
results : response.data
})
this.componentUpdate();
}) Deals with the error
.catch(err => console.log(err))

13
Request Config
url: url is the server URL that will be used for the request

method: method` is the request method to be used when making the request

baseURL: will be prepended to `url` unless `url` is absolute

transformRequest: [function (data, headers) {


allows changes to the request data before it is sent to the server
return data;
}]

transformResponse: [function (data) {


allows changes to the response data to be made before
return data;

maxRedirects: defines the maximum number of redirects to follow in node.js with default
value 5

headers: {'X-Requested-With': 'XMLHttpRequest'},


14
Request Config Continued…..
params: { are the URL parameters to be sent with the request }

data: { the data to be sent as the request body }

timeout: specifies the number of milliseconds before the request times out,

auth: {
username: 'janedoe',
password: 's00pers3cret'
}

responseType: indicates the type of data that the server will respond with default “json”

maxContentLength: defines the max size of the http response content allowed

validateStatus: function (status) {


defines whether to resolve or reject the promise for a given
}

15
Request Config Example

POST

method: ‘post’,
url: '/user/12345’,
data: {
firstName: 'Sam’,
lastName: 'Mathew’
}

GET

method: ‘get’,
url: '/user/12345’,
responseType: 'stream'

16
Demo For GET

Fetching information using https://trainingdata-13117.firebaseio.com/courses.json

17
Demo for GET Continued…..
Step 1 : Create axios instance

const api = axios.create({


baseURL: "https://trainingdata-13117.firebaseio.com"
})

Step 2 : Call the Api inside componentDidMount()

componentDidMount(){
// course List Fetchig
api.get("/courses.json")
.then((response) => {
this.setState({
results : response.data
})
})
.catch(err => console.log(err))
}

18
Demo For POST

Storing information using https://trainingdata-13117.firebaseio.com/registeredCourse.json

19
Demo for POST Continued
Step 1 : Create a form adding Participant ID, Participant Name, Course Date and List of Courses with
Checkbox

Step 2 : Create a method to post the data using POST Api

registerParticipant(){
let body = JSON.stringify({
"partName" : this.refs.partName.value,
"partID" : this.refs.partID.value ,
"courseDate" : this.refs.courseDate.value,
"selectedCourse" : this.state.selectedCourse
})
api.post("/registeredCourse.json",body)
.then((response) => {
console.log(response);
T }).catch(err => console.log(err));
}

20
Passing parameter in Get request
While requesting data from REST API , it is
also possible that client may need only
specific data instead of complete data

This can be achieved by passing


parameter in the get request

Parameter can be passed either directly in


the url or by defining it as “params” within
get request

21
Demo - Passing parameter in Get request
Modify existing component(HttpDemo.js)

22
Demo - Passing parameter in Get request -
Explanation

Only the data specific


to userID=3 is displayed

23
Demo - Passing parameter in Get request
Output on
browser console

24
Activity - 1
Display the Registered Courses using GET API

25
Activity - 2
Add a Course Component which will store the data in courses.json POST API

26
Module Summary
Now, you should be able to:
• Basics of Http

• Http methods and when to use which method

• How axios helps to communicate http

27
Thank You

28

You might also like