Skip to content

Commit 8079518

Browse files
Merge pull request #474 from codebar/replace-js-api-tutorials-for-vonage
Replace BBC API tutorials for Vonage
2 parents d4780cb + d479c33 commit 8079518

5 files changed

Lines changed: 56 additions & 244 deletions

File tree

index.html

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,8 @@ <h3>JavaScript</h3>
5757
<li><a href="js/lesson1/tutorial.html">Lesson 1 - Introduction to JavaScript</a></li>
5858
<li><a href="js/lesson2/tutorial.html">Lesson 2 - Expressions, Loops and Arrays</a></li>
5959
<li><a href="js/lesson3/tutorial.html">Lesson 3 - Introduction to jQuery</a></li>
60-
<li><a href="js/lesson4/tutorial.html">Lesson 4 - HTTP Requests, AJAX and APIs</a></li>
60+
<li><a href="js/lesson4/tutorial.html">Lesson 4 - Introduction to HTTP Requests and APIs</a></li>
61+
<li><a href="js/lesson4a/tutorial.html">Lesson 4a - API's part 2 - Send yourself an SMS with Vonage</a></li>
6162
<li><a href="js/lesson5/tutorial.html">Lesson 5 - HTTP Requests, AJAX and APIs (part 2)</a></li>
6263
<li><a href="js/lesson6/tutorial.html">Lesson 6 - Drawing in Canvas</a></li>
6364
<li><a href="js/lesson7/tutorial.html">Lesson 7 - Introduction to Testing</a></li>

js/lesson4/tutorial.md

Lines changed: 23 additions & 243 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
---
22
layout: page
3-
title: HTTP Requests, AJAX and APIs
3+
title: HTTP Requests and APIs
44
---
55

66
### Objectives
77

88
In this tutorial we are going to look at:
99

10-
* The HTTP protocol
10+
* HTTP Requests
1111
* APIs
12-
* AJAX
1312
* JSON
1413
* Loading API data into web pages
1514
* Using jQuery AJAX functionality
@@ -18,36 +17,27 @@ In this tutorial we are going to look at:
1817

1918
By the end of this tutorial you will have built:
2019

21-
* A webpage that can retrieve information about a specified GitHub user
22-
* A webpage that can show the upcoming schedule for BBC shows
20+
* A webpage that can retrieve information from a GitHub user
2321

24-
# HTTP Requests
22+
## HTTP Requests
2523

26-
## What are HTTP Requests?
24+
### What are HTTP Requests?
2725

28-
Every time the browser fetches data from a server (which could be a page, an image, a script etc) it does it using HTTP. HTTP is the **H**&#x200b;yper<strong>T</strong>ext **T**&#x200b;ransport **P**&#x200b;rotocol. The server then sends back a **response**. An API is an easy way of fetching information from a remote service, in a way that's easy for a computer to understand.
26+
**H**&#x200b;yper<strong>T</strong>ext **T**&#x200b;ransport **P**&#x200b;rotocol
2927

30-
GitHub offers a [simple API](https://www.githubstatus.com/api/) for viewing its current and historical server availability.
28+
Every time the browser fetches data from a server (which could be a page, an image, a script etc) it does it using HTTP. The server then sends back a **response**. An API is an easy way of fetching information from a remote service, in a way that a computer can understand, typically in **JSON** format (we'll talk more about JSON later).
3129

32-
> Availability means whether or not the GitHub website was accessible to users and accepting traffic. If your website is down, it is not available.
30+
GitHub offers a [simple API](https://www.githubstatus.com/api/) for viewing its current and historical server availability. Availability means whether or not the GitHub website was accessible to users and accepting traffic. If your website is down, it is not available.
3331

34-
You can access an API in your web browser. Just pop the following into the address bar:
32+
You can access an API in your web browser. Pop the following into the address bar:
3533

3634
https://www.githubstatus.com/api/v2/summary.json
3735

38-
If you are on a mac or a linux/unix machine, you can access the API using curl:
39-
40-
curl https://www.githubstatus.com/api/v2/summary.json
41-
42-
> Paste the following command into Terminal, which you can find in Finder - first go into the Applications folder, then Utilities.
43-
44-
Here is an example of the **GET** requests issued by the [wishlist tutorial](https://tutorials.codebar.io/examples/wishlist/index.html).
45-
46-
\*You can view any requests issued by a website by going to the Network (or Net) tab.
36+
You can view all requests issued by a website by going to the Network (or Net) tab.
4737

4838
![](assets/images/inspector_requests.png)
4939

50-
As part of the response, a request gives back a **status code**. You can use this to identify if the request was successful or not.
40+
As part of the response, a request gives back a **status code**. You can use this to identify if the request was successful or not. Below is a list of the most common status codes.
5141

5242
| Status code | Message | Description |
5343
| ------------| ------- | ------------ |
@@ -56,23 +46,17 @@ As part of the response, a request gives back a **status code**. You can use thi
5646
| 400 | Bad Request | The server did no understand the request |
5747
| 404 | Not Found | The server could not find the requested resource |
5848

59-
### HTTP Verbs
49+
### HTTP Methods
6050

61-
HTTP verbs are sent by the browser or client, and along with the URL used and data transmitted form part of the instruction to the API. There are several verbs, but in this tutorial we will be primarily using GET. GET is used to fetch information from an API. Another common verb is POST, which is used to create a new object on the remote service.
51+
There are several HTTP Methods, but in this tutorial we will primarily be using **GET** and **POST**. GET is used to request data from your specified API, whereas POST is used to send data to your specified API.
6252

6353
## Exercise 1 - Retrieve GitHub user information
6454

65-
We'll build a small application that gives us back information about a GitHub user - we want to show their username, information and their picture. [Download](https://gist.github.com/deniseyu/d1bc03b8091153b4b1a7/download) the exercise files or clone them directly from Github `https://gist.github.com/deniseyu/d1bc03b8091153b4b1a7`
66-
67-
GitHub offers an API where you can request information for a given username. The verb to use is GET, and the url is `https://api.github.com/users/<username>`. For codebar, this would be: `https://api.github.com/users/codebar`. Again, to request this you can use curl:
55+
We are going to build a small application that requests information about a GitHub user - we want to show their username, information and picture.
6856

69-
$ curl -XGET https://api.github.com/users/codebar
57+
> Take a second to think about what HTTP Method we will use to retrieve this data. Is it GET or POST?
7058
71-
or, as GET is the default verb, just:
72-
73-
$ curl https://api.github.com/users/codebar
74-
75-
Again, you can simply access this URL in your web browser by inserting `https://api.github.com/users/codebar` into the address bar.
59+
If you guessed GET congrats! Now let's retrieve some data. See what happens when you put `https://api.github.com/users/codebar` into your address bar.
7660

7761
The response will look something like the JSON data below, which we have shortened:
7862

@@ -96,8 +80,12 @@ The response will look something like the JSON data below, which we have shorten
9680

9781
This data is what's called key value pairs, meaning that the name of the field is displayed immediately before the value. As you can see, the URL for the avatar (user's icon) is in the `avatar_url` field, and is `https://avatars.githubusercontent.com/u/9906?v=2`.
9882

83+
> Run the same URL but with your GitHub name.
84+
9985
### Getting started
10086

87+
Now [Download](https://gist.github.com/deniseyu/d1bc03b8091153b4b1a7/download) the exercise files or clone them directly from Github `https://gist.github.com/deniseyu/d1bc03b8091153b4b1a7`.
88+
10189
First, open the HTML page supplied in the download. As you can see, there is a box to type in a username. When the user has typed in the username, they should be able to trigger the API call to GitHub by pressing \<enter\>.
10290

10391
The following code allows you to listen for a keypress on the input field, and to see if it was the \<enter\> key that was pressed.
@@ -147,13 +135,13 @@ function getGithubInfo(username) {
147135

148136
We create an `XMLHttpRequest` object and then call the `open` method, passing three arguments to the GitHub API.
149137

150-
1. the `verb` - in this case, `'GET'`
138+
1. the `method` - in this case, `'GET'`
151139
2. the `url` - in this case the url eg https://api.github.com/users/codebar
152140
3. whether or not to run this request synchronously or asynchronously.
153141

154142
In this case, we'll specify synchronously by passing `false`. This means the browser will wait for the call to the GitHub API to finish before continuing.
155143

156-
> Making requests synchronously is not good practice, but we're doing it for now to keep things simple. Your browser may show a deprecation warning but the request will still work. We'll move onto asynchronous requests further down once we have the basics of APIs covered.
144+
Making requests synchronously is not good practice, but we're doing it for now to keep things simple. Your browser may show a deprecation warning but the request will still work. We'll move onto asynchronous requests further down once we have the basics of APIs covered.
157145

158146
You can now call `getGithubInfo`, passing the username, from the `keypress` block above. That will log the data to the console. Next, we need to pass this back to the web page via the DOM.
159147

@@ -228,213 +216,5 @@ Well done, you've finished! For a bonus, switch your `getGithubInfo` method to r
228216
> Coach... explain the difference between synchronous and asynchronous requests. There's a good explanation on [Mozilla Developer Network (MDN)](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests)
229217
230218

231-
## ~~Exercise 2 - BBC's tomorrow's TV schedule~~
232-
233-
![](https://cdn0.iconfinder.com/data/icons/shift-free/32/Error-128.png)
234-
235-
**Part 2 of this exercise is no longer possible as the API that it uses has been taken down by the BBC.**
236-
**Sorry, we're working on fixing the exercise!**
237-
238-
[Download](https://gist.github.com/despo/05cab2f0b38bc02318e7/download) the exercise files or clone them directly from github `git clone https://gist.github.com/05cab2f0b38bc02318e7.git`
239-
240-
For the second exercise, we will build an application that retrieves tomorrow's TV schedule for each genre using BBC's API.
241-
242-
### What we will be doing:
243-
244-
1. Retrieve and render available genres using `http://www.bbc.co.uk/tv/programmes/genres.json`
245-
246-
2. Write a function that retrieves tomorrow's TV schedule using a genre `http://www.bbc.co.uk/tv/programmes/genres/<genre>/schedules/tomorrow.json`
247-
248-
3. Write a function that displays each programme
249-
250-
4. **Bonus** Retrieve all upcoming episodes of a programme
251-
252-
### Request using jQuery
253-
254-
This time, let's use jQuery's `ajax()` method. Things are a bit easier when using jQuery as we can create different code blocks that handle successful or failed requests.
255-
256-
Also, jQuery isolates us from the differences between browser implementations of AJAX calls (for example, if we wanted to make the previous AJAX call work in Internet Explorer, we will have to write [a much longer method](http://www.tutorialspoint.com/ajax/ajax_browser_support.htm)!)
257-
258-
```js
259-
$.ajax({
260-
url: request_url,
261-
dataType: 'json',
262-
beforeSend: function() {
263-
// do something before running the request
264-
}
265-
}).done(function(data) {
266-
// process data
267-
}).fail(function() {
268-
// code
269-
}).always(function() {
270-
// code that runs regardless of request succeeding or failing
271-
});
272-
```
273-
274-
`datatype` defines the type of result we will be getting back. This avoids us having to parse the response to JSON.
275-
276-
`beforeSend` can be used if we need to perform something before running the request.
277-
278-
`.done()` handles a response that returns a success status code
279-
280-
`.fail()` is called when the request fails
281-
282-
283-
## Retrieving and displaying all available genres
284-
285-
Write a function `retrieveGenres()` that does an AJAX call to the API.
286-
287-
```javascript
288-
function retrieveGenres() {
289-
// AJAX call using jQuery that retrieve and process the result
290-
}
291-
```
292-
> Try logging the resulted data and have a look in the console to see and explore the created objects
293-
294-
> `<key>` is the genre format we need to retrieve results from the API
295-
296-
> You can use `<title>` to display a humanly readable format of the Genre
297-
298-
As you can see from the console, the resulting objects are returned inside an Array. We want to iterate over the list using the native Array `forEach( )` function and add each item to the `#genres` list, as a **list item**. As we need to have access to the `key` as well, we can set that as the list item's `id`.
299-
300-
Now that we have all the available genres, we can move on to making calls to the API using the genre to retrieve tomorrow's schedule!!
301-
302-
## Retrieve schedule
303-
304-
Now, let's create a function that retrieves films using genre.
305-
306-
```javascript
307-
function getTomorrowsSchedule(genre) {
308-
// call to retrieve TV schedule
309-
}
310-
```
311-
312-
The response you get back should look similar to this, with multiple objects in the broadcasts array.
313-
314-
```json
315-
{
316-
"broadcasts": [
317-
{
318-
"is_repeat": false,
319-
"is_blanked": false,
320-
"schedule_date": "2014-01-15",
321-
"start": "2014-01-15T00:10:00Z",
322-
"end": "2014-01-15T01:50:00Z",
323-
"duration": 6000,
324-
"service": {
325-
"type": "tv",
326-
"id": "bbc_one",
327-
"key": "bbcone",
328-
"title": "BBC One",
329-
"outlets": [
330-
{
331-
"id": "bbc_one_wales",
332-
"key": "wales",
333-
"title": "Wales"
334-
},
335-
{
336-
"id": "bbc_one_wales_hd",
337-
"key": "wales_hd",
338-
"title": "Wales HD"
339-
}
340-
]
341-
},
342-
"programme": {
343-
"type": "episode",
344-
"pid": "b00sbk03",
345-
"position": null,
346-
"title": "Disturbia",
347-
"short_synopsis": "Thriller about a high school student convinced that his neighbour is a serial killer.",
348-
"media_type": "audio_video",
349-
"duration": 6000,
350-
"image": {
351-
"pid": "p01gqbj3"
352-
},
353-
"display_titles": {
354-
"title": "Disturbia",
355-
"subtitle": ""
356-
},
357-
"first_broadcast_date": "2010-05-03T22:30:00+01:00",
358-
"ownership": {
359-
"service": {
360-
"type": "tv",
361-
"id": "bbc_three",
362-
"key": "bbcthree",
363-
"title": "BBC Three"
364-
}
365-
},
366-
"is_available_mediaset_pc_sd": false,
367-
"is_legacy_media": false
368-
}
369-
}]
370-
}
371-
```
372-
373-
To process the response, we want to iterate over the `response.broadcasts` array and add each item, to `#programmes` as a list item.
374-
375-
To make this a bit easier, this is how you can access the values we need:
376-
377-
* `item.programme.display_titles.title`
378-
* `item.programme.short_synopsis`
379-
* `item.programme.image.pid` _only if `item.programme.image` is set_
380-
* `item.start` and `item.end`
381-
* `item.duration`
382-
* `item.service.title`
383-
384-
It would be easier to use string concatenation to construct the html, before appending each item to the list.
385-
Also, to make your code easier to read, try constructing the html in a method that you pass the response object.
386-
387-
```javascript
388-
function processEpisode(episode) {
389-
var item_html = '<li>';
390-
item_html += '<h2>' + episode.programme.display_titles.title + '</h2>';
391-
// display short short synopsis
392-
// display image
393-
// display date and time
394-
// display duration (HINT: the duration is in seconds, convert that to minutes)
395-
// display the channel (or service, as its called by the API) - add this in a span with the class `service`
396-
...
397-
}
398-
```
399-
400-
> To display the date formatted correctly, you can use the `formatDate( )` function as we won't be going into details about dates in this tutorial. If you want to know how it works, try going through the code and ask your coach any questions you have.
401-
402-
To display an image for a programme, we need to use `<img src=http://ichef.bbci.co.uk/images/ic/272x153/<pid>.jpg />`. As not all programmes have an image, we can use an image placeholder when no image is set `<img src='http://placehold.it/272x153' />`
403-
404-
### Binding the call to the click event
405-
406-
Handle a `click` event on `#genres li` and make a call to `getTomorrowsSchedule(genre)`
407-
408-
### Improving our function
409-
410-
To make the genre we have just clicked active, we also want to add the CSS class `active` to the element that the event has been triggered from. Don't forget to remove the class `active` from any other `#genres li` items.
411-
412-
> Did you remember to commit your changes?
413-
414-
### Using `beforeSend`
415-
416-
Every time we issue a call to the API, we want to clear the `#programmes` list. We can do that using `empty()`.
417-
Also, as some of the requests take a while, we want to display a spinning image `<div class='spinner'><img src='spinner.gif' /></div>`.
418-
419-
> Don't forget to remove the spinner, when the request is completed successfully.
420-
421-
## Bonus: Retrieving all upcoming episodes of a programme
422-
423-
To get back all the upcoming shows for an episode, we need to utilise the programme pid, that we can retrieve from the response using `episode.programme.programme.pid`. The URL for the request is `http://www.bbc.co.uk/programmes/<pid>/episodes/upcoming.json`
424-
425-
> **Hint:** The programme `pid` is only available if `episode.programme.position` is set.
426-
427-
428-
```javascript
429-
function getUpcomingEpisodes(pid) {
430-
// AJAX call to retrieve upcoming episodes
431-
}
432-
```
433-
Since the response structure is similar to the one for retrieving tomorrow's schedule, we should be able to re-use the `processEpisode( )` function to display each item from the broadcasts array.
434-
435-
Handle the `click` event to retrieve and display the upcoming episodes!
436-
437-
Here is our version of the [tv schedule app](../../examples/tv-schedule/index.html).
438-
439219
---
440-
This ends our **HTTP Requests, AJAX and APIs** tutorial. Is there something you don't understand? Try and go through the provided resources with your coach. If you have any feedback, or can think of ways to improve this tutorial [send us an email](mailto:feedback@codebar.io) and let us know.
220+
This ends our **HTTP Requests and APIs** tutorial. Is there something you don't understand? Try and go through the provided resources with your coach. If you have any feedback, or can think of ways to improve this tutorial [send us an email](mailto:feedback@codebar.io) and let us know.
96.5 KB
Loading

js/lesson4a/tutorial.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
layout: page
3+
title: API's part 2 - Send yourself an SMS with Vonage
4+
---
5+
6+
### Goal
7+
8+
By the end of this tutorial you will have:
9+
10+
* Sent yourself an SMS using the Vonage API
11+
12+
## Refresh
13+
14+
From the previous tutorial you learnt how HTTP requests work, the different between **GET** and **POST** and status codes. If you need a refresher pop back to the previous tutorial to remind yourself.
15+
16+
## Exercise - Send yourself an SMS with the Vonage API
17+
18+
<img src="./assets/images/VonageLogo.png" alt="Vonage Logo" width="350px">
19+
20+
In the following Vonage API tutorial you will create an account, and send yourself an SMS. Just a heads up, it will involve you creating an account and giving your phone number.
21+
22+
When signing up select NodeJS as your language. NodeJS is a runtine enviroment that allows you to run JavaScript on the server than in the browser which is what you would've been doing if you've followed our first few JavaScript tutorials.
23+
24+
[Send yourself an SMS with the Vonage API](https://developer.nexmo.com/?utm_source=codebar&utm_campaign=Events&utm_medium=bitly&utm_source=Events)
25+
26+
---
27+
This ends our sponsored Vonage tutorial **API's part 2 - Send yourself an SMS with Vonage**. Is there something you don't understand? Try and go through the provided resources with your coach. If you have any feedback, or can think of ways to improve this tutorial [send us an email](mailto:feedback@codebar.io) and let us know.

stylesheets/styles.css

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ p, ul, ol, table, pre, dl {
1616
margin: 0 0 20px;
1717
}
1818

19+
li {
20+
line-height: 25px;
21+
}
22+
1923
h1, h2, h3 {
2024
line-height: 1.1;
2125
}

0 commit comments

Comments
 (0)