-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-request-lec.html
More file actions
269 lines (219 loc) · 10.6 KB
/
Copy pathhttp-request-lec.html
File metadata and controls
269 lines (219 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
<!--
1. HTTP or Hypertext Transfer Protocol
* Is the foundation of data communication on the world wide web.
* It defines the rules for how messages (requests and responses) are formatted and transmitted between web browsers and web servers.
* It's the protocol that enables the retrieval of web pages and the exchange of data on the internet.
* For example, when a user wants to view a web page, their web browser (in this case the web browser is the client) sends an HTTP request to the server (which the server is the remote computer) hosting the desired content. The server then responds with an HTTP response, providing the requested data or indicating an error.
// Request made from Client(frontEnd)
// Response handled by Server(backEnd)
Some common type of REQUESTS (also called HTTP Methods) are
* GET
- Purpose: Is to retrieve data from the server
- Example: Fetching a webpage, retrieving data from a server
* POST
- Purpose: Is to submit data to be processed to a specified resource
- Example: Submitting a form, uploading a file.
* PUT
- Purpose: Is to update a resource or create a new resource if it doesn't exist
- Example: Updating a user's profile, uploading a resource to a specific URL
* PATCH
- Purpose: Is to apply partial modifications to a resource
- Example: Updating specific fields of an existing resource
Example: partially update something that exists
* DELETE
- Purpose: Is to remove or delete
- Example: Removing a file, deleting a user account.
2. What is an API
* API stands for "Application Programming Interface" and is a way of describing software design.
* At the highest level an API is any application with a set of instruction for how programmers can interact with getting data.
* APIs can be implemented using HTTP as a communication protocol. They define endpoints (URLs) and rules for how data should be requested and sent.
* There are APIs for (weather, maps, stocks, books, sports, art, games, movies, etc...). Some are free, some are somewhat expensive and some are really expensive.
* Here is a good list of Free Apis (https://github.com/public-apis/public-apis)
*ex:URL that contains information, API is an endpoint URL
- API Data
* An API will receive a scripted request and send a response. That data will generally be in one of two forms: XML or JSON.
* XML stands for "eXtensible Markup Language" and is the granddaddy of serialized data formats (itself based on HTML). XML is fat, ugly and cumbersome to parse. It is increasingly the less common of the two formats you'll encounter.
* XML looks like this:
<users>
<user id="23">
<name><![CDATA[Bob]]></name>
</user>
<user id="72">
<name><![CDATA[Tim]]></name>
</user>
</users>
* JSON or JavaScript Object Notation is structured data (i.e., arrays and object). JSON has become a universal standard for sending and receiving data across the web. It is light-weight, easy-to-read and quick to parse.
* JSON is based off the JavaScript Object syntax, and is just a long string of characters. One notable difference is that double quotes must always be used for keys and values.
* JSON looks like this:
{
"users": [{ "name": "Bob", "id": 23 }, { "name": "Tim", "id": 72 }],
"content": "This is a piece of content"
}
3. What is AJAX or Asynchronous JavaScript and XML.
* AJAX is the concept of communicating with a server, sending or retrieving data, without refreshing the current webpage.
* AJAX uses HTTP to send requests to APIs.(ex:GIT,POST,etc.) These requests can retrieve data in various formats, not just XML, despite the name.
* For example, back in the early internet day, whenever we are making a request to a page, the entire page had to refresh and reload. Whenever we change some type of data the entire page had to reload. Imagine we were on instagram's website and everytime we hit a like instead of it just turning blue and just incrementing, the entire page refreshed, and then it take you back to where you were, and it was incrementing. If you had to like again or de-like it would refresh again. You can imagine that was really annoying. So ajax came around for way for us to make request and not have our page refresh, it was a way for us to asynchronously go out and do some type of request and let the rest of our javascript run while request was happening.
In simpler terms:
* HTTP is the protocol that enables communication on the web.
* API is a set of rules that allows different software to talk to each other, often implemented using HTTP.
* AJAX is a technique that uses JavaScript and HTTP to make dynamic requests to a server without reloading the entire web page. It often involves interacting with APIs to get or send data.
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id="searchForm">
<input type="text" id="searchBar" placeholder="Please enter a pokemon">
<input type="submit" id="searchButton" value="Search">
</form>
<p class="books"></p>
<div class="container"></div>
<script>
// fetch takes an endpoint URL
// //Fetch generates a Promise Object-ex:server getting coffee
// let something = fetch("https://pokeapi.co/api/v2/pokemon/")
// // console.log(something)
// //.then() will wait for the Promise
// //.then() can be chained
// .then(function(response) {
// return (response.json())
// })
// .then(function(data) {
// console.log(data)
// })
//example of how callback function and arrow functions cleans up the code nicely
// let something = fetch("https://pokeapi.co/api/v2/pokemon/charmander")
// .then(response => response.json())
// .then(data => console.log(data))
// .catch(error => console.log("Error" + error))
// //similar to the default in a case switch, .finally will happen whether error or not
// .finally(console.log("This will run no matter what"))
//ok response
// fetch("https://pokeapi.co/api/v2/pokemon/charmander")
// .then( response => {
// if(!response.ok) {
// console.log("unsucessful");
// }
// return response.json();
// })
// .then( data => console.log("At last, we have the JSON data we want: " + data))
//
// .catch( error => {
// console.log("ERROR!!!");
// console.log("Error message: " + error.message);
// })
// .finally( () => console.log("This function always runs!"));
//show ASYNC behavior
//storing method in options
// const options = {
// method: "GET",
// headers: { "Content-Type": "application/json" },
// // body: JSON.stringify(data),
// }
//
// fetch("https://pokeapi.co/api/v2/pokemon/charmander", options)
// .then(response => {
// console.log(2);
// return response.json()
// })
// .then(data => console.log(data));
// console.log(3);
//
//
//
//
// fetch('https://api.github.com/users')
// .then(response => response.json())
// .then(users => {
// users.forEach( user => {
// // log each user's username (or login property)
// console.log(user.login);
// })
// })
// .catch(error => console.error(error));
//For Ratatta pokemon, make an Ajax call and console.log its weight and height
//api url returns a promise, promise to response
let rattata = fetch("https://pokeapi.co/api/v2/pokemon/rattata")
// 1.then waiting for response from the server
.then(response => response.json())
// 2.then waiting for conversion of data from jason
//Reminder: When using the console.log on multiple lines, will need the curly braces on the arrow function
.then(pokemonData => {
console.log(pokemonData.weight)
console.log(pokemonData.height)
})
.catch(err => console.log(err))
//concatenate using one console.log
// .then(data => console.log(`weight: ${data.weight}, height: ${data.height}`))
// function getGithubUsernames() {
// return fetch('https://api.github.com/users')
// .then(response => response.json())
// }
fetch('https://api.github.com/users')
.then(response => response.json())
.then(users => {
users.forEach( user => {
// log each user's username (or login property)
console.log(user.login);
})
})
.catch(error => console.error(error));
///************
// function getGithubUsernames() {
// return fetch('https://api.github.com/users')
// .then(response => response.json())
// }
// later on...
//
// getGithubUsernames().then( users => {
// users.forEach( userObj => {
// // do something with each username
// console.log(userObj.login);
// });
// }).catch(error => console.error(error));
//*******
function createPokemonElements(data) {
const paragraph = document.createElement('p');
paragraph.innerHTML = data.name;
const container = document.querySelector('.container');
container.appendChild(paragraph)
//image
const image = document.createElement('img');
//set to src vs innerHTML for images
image.src = data.sprites.front_shiny
container.appendChild(image);
image.style.height = "200px";
}
function onFail(error) {
console.log("Error", error)
}
const searchForm = document.querySelector("#searchForm");
searchForm.addEventListener('submit', function (event) {
event.preventDefault();
const input = document.querySelector("#searchBar").value;
// console.log(input)
fetch(`https://pokeapi.co/api/v2/pokemon/${input}`)
.then(res => res.json())
.then(data => createPokemonElements(data))
})
function processBooks(book) {
for(let i = 0; i < book.length; i++) {
document.querySelector(".books").innerHTML +=
book[i].title + '\n';
}
}
fetch("data/data.jason")
.then(res => res.json())
.then(data => processBooks(data))
fetch(url, {headers: {'Authorization': 'token' + }})
</script>
<script src="js/keys.js"></script>
<script src="js/index.js"></script>
</body>
</html>