Using AJAX to Consume a REST Web API
Announcements
- How is the term project going?
1. Intro to course and Identity |
6. |
2. Authentication and Authorization | 7. Creating a Web Service |
3. Claims and Third Party Authentication |
8. Consuming a
Web Service |
4. Web Security |
9. Docker Containers |
5. Publishing to a Production Server | 10. Term Project |
This week you will learn how to create a web page that serves as a client to a REST web service. Your web page will use JavaScript and the DOM's XMLHttpRequest object to intereact with the web API.
The XMLHttpRequest JavaScript object, which is part of the DOM in all modern browsers, lets you retrieve data from a URL without having to do a full page refresh. XMLHttpRequest was originally designed by Microsoft around 1999 and later adopted by Mozilla, Apple, and Google. Since October 2014, it has been part of the standard. Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp).
function responseListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", responseListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
Follow the strategy for writing a REST client in JavaScript described in the tutorial by Geoffey Liu (2016).
app.UseStaticFiles();
Newer JavaScript web clients use the fetch() method rather than the older
XMLHttpRequest() (XHR) method. Both methods are
asynchronous, but fetch uses promises rather than the older
style JavaScript call-backs.
There are several modern alternatives to REST or SOAP for
communicating with a web API. Two of them are: