Lect05 Fetch APIs
Lect05 Fetch APIs
Lecture 5
Fetch & APIs
Today’s Contents
fetch("http://www.weather.com")
● Request menu
● Order pizza
● Check pizza
● Eat pizza
● Pay for pizza
At each step, can’t continue before the previous finishes. We as the client
(pizza eaters) need the server (pizza provider) to do something on our behalf.
Fetching Data Asynchronously
But we have to be careful because the Internet is an “unusual” place and full of
surprises!
● What kind of data can we get from the Internet?
● How do we request data from the Internet?
● What happens when something goes wrong on the Internet?
● Can you trust everything you find on the Internet?
Asynchronous JavaScript and (XML)* -- "AJAX"
An application programming
interface (API) is a communication
protocol that allows two pieces of
software to communicate.
(function(){
...
function doWebRequest() {
const url = "....."; // put url string here
fetch(url); // returns a Promise!
}
...
})();
AJAX with fetch
fetch was created in 2014 and incorporated into the global window.
fetch takes a URL string as a parameter to request data (e.g. menu category
JSON) that we can work with in our JS file.
function populateMenu() {
const URL = "https://hanustartup.org/wpr/api";
fetch(URL + "/getCategories.php") // returns a Promise!
.then(...)
.then(...)
.catch(...);
}
We need to do something with the data that comes back from the server.
But we don't know how long that will take or if it even will come back correctly!
The fetch call returns a Promise object which will help us with this
uncertainty.
AJAX fetch Code Skeleton
Operation, Parameters
Host (sever) location
(aka the requested resource)
💻
Request URL: https://xkcd.com/869/info.0.json
fetch data (whether it's // Step 1. Write a function to "fetch" data from a URL
HTML, txt, JSON, etc) function makeRequest() {
let url = BASE_URL + "/api?query0=value0"; // some requests require parameters
we use a function in fetch(url)
.then(statusCheck)
JavaScript called //.then(resp => resp.text()) // use this if your data comes in text
fetch, which takes a //.then(resp => resp.json()) // or this if your data comes in JSON
.then(processData)
URL path to fetch data .catch(handleError); // define a user-friendly error-message function
from. }
// Step 2: Implement a function to process the data. You may want to break this apart
● Here's the general // into multiple functions.
function processData(responseData) {
template you will use // Do something with your responseData! (build DOM, display messages, etc.)
for most AJAX code: }
res.text()
url
catch()
catch()
catch()
handleError catch()
Every API has four components:
1. Where is the server that's running the API? (I.e., what's the hostname?)
2. Are we allowed to access it?
3. What content does the API give us?
4. What format should the request for content be in? What format does the
response come back in?
Fetching data from a web service
4. What format we get answers in (the response data format, preferably text or JSON)
Fetching data from a web service
function makeRequest() {
let requestString = "https://api.nasa.gov/planetary/apod?" +
"api_key=DEMO_KEY&date=2022-02-22";
fetch(requestString)
.then(statusCheck) // 1
.then(resp => resp.json()) // 2
.then(processData) // 3
.catch(handleError); // 4
}
● Security measure browsers have implemented that restricts one site from
accessing resources in another unless explicitly given permission.
● Most of the APIs that are demoed in this lecture have explicitly allowed *,
meaning anyone.
● Many APIs you run into around the Internet will be locked more tightly.
Regular Expressions!
/^[a-zA-Z_\-]+@(([a-zA-Z_\-])+\.)+[a-zA-Z]{2,4}$/
/abc/
Write a regex for Student ID numbers that are exactly 7 digits and start with 1
Practice exercise
Write a regex for Student ID numbers that are exactly 7 digits and start with 1
Solution: /1\d{6}/
Regular Expressions in JavaScript
Regex can be a very handy tool with JS as well, from validation to fun find/replace features.
There are two common ways regex can be used:
● With the RegExp constructor (either with a literal or string, useful because you don't
always know what the pattern is, such as user input)
● With a literal (when you know exactly what the regex pattern is, evaluated exactly
once)
(*) Note that we don't use "/" when using strings for patterns in the second RegExp
constructor. This can be useful when we want to search for a particular pattern given as text
input (e.g. a word replacer tool)!
Some Regex Functions in JS
Regex Objects have a few useful functions that take strings as arguments
regex.test(string) returns a boolean if a string matches the regex
Some JS string methods can take Regular Expressions, like match, search, and replace
string.match(regex) returns an array of information about a match, including the index
of the first match
GET POST
● Requesting data from a server using ● Data sent in the HTTP message
filters (URL parameters) body, not the URL
● Should never be used when dealing ● Not cached or bookmarked, no
with sensitive data restrictions on data length
● Can be cached and bookmarked, ● POST is commonly used with
remains in browser history forms! However, not exclusively
with forms
function requestMenu() {
let data = new FormData();
data.append("key1", "value1"); // repeat for as many params as necessary
data.append("key2", "value2");
There are two ways you'll commonly see forms used with POST
● As soon as the submit button is clicked on this page, the data is sent to the
web service and the page is refreshed with the response (sometimes
redirecting).
● This is becoming less common because we lose the asynchronous features of
requests.
<form id="input-form">
City: <input name="city" type="text">
State: <input name="state" type="text">
ZIP: <input name="zip" type="number">
<button id="submit-btn">Submit!</button>
</form>
When an input is in a form along with a button, clicking the button automatically verifies the
input and does a POST request. If you do not want the page to refresh, you must use
preventDefault to override default form submission behavior (used in previous example).
function someFunction() {
id("input-form").addEventListener("submit", function(e) {
// Fires when submit event happens on form
// If we've gotten in here, all HTML5 validation checks have passed
e.preventDefault(); // prevent default behavior of submit (page refresh)
submitRequest(); // intended response function
});
User input validation is the process of ensuring that any user input is well-formed
and correct (valid).
Most importantly, don't trust that users will provide correct/safe input!
A Form Example
<input type="number">
We can limit the up and down arrows with min (and max if we choose)
To insist that there is a value in the input field we can add required
To prevent a user from being able to type in erroneous values, we can add a regular
expression to the required attribute
Forms are HTML elements that can be used to "package" user input values based
on the name attribute, often used with POST requests. There are many neat ways
to perform validation with the right choice of form elements!
<form>
<label for="city">City: </label>
<input name="city" id="city" type="text" required>
<label for="state">State: </label>
<input name="state" id="state" type="text" size="2" maxlength="2" required>
<label for="zip">ZIP: </label>
<input name="zip" id="zip" type="number" size="5" min=10000 max=99999 required>
<button id="submit-btn">Submit!</button>
</form>