layout | title |
---|---|
page |
HTTP Requests, AJAX and APIs (part 2) |
This is the second tutorial on HTTP Requests, AJAX and APIs. You can find the first part of the tutorial.
In the last lesson we learnt that an HTTP Request is when we ask the server for some information.
In the two earlier exercises we used the GET request. Today we will be building a Hangman game using an existing API that will handle the game logic for us. Additionally, we will explore modern methods like the Fetch API for making HTTP requests in JavaScript.
We will be using the POST, PUT and GET requests, and other things we've learned in the last couple of lessons.
Verb | Description |
---|---|
GET | Fetching a resource (e.g. /index.html will return the HTML of the page) |
PUT | Updating an existing resource. |
POST | Create a new resource. |
To use POST and PUT requests we must specify the type
in the ajax()
call that we introduced in the previous lesson.
You can also specify any data
as a JSON object.
$.ajax({
type: request_type,
data: { field: 'value', other_field: 'other value' }
...
});
The Fetch API is a modern way to make HTTP requests in JavaScript. Unlike $.ajax(), Fetch API uses Promises to handle responses, making it more readable and flexible.
So Why Use Fetch?
✔ Uses Promises, making it easier to handle responses. ✔ More readable and modern compared to older methods. ✔ Supports asynchronous operations efficiently.
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
You can paste the code below into online editors like JSFiddle or CodePen. For example, you can search username codebar in the input bar.
<input type="text" id="username" placeholder="Enter GitHub username" />
<button id="fetchButton">Get User Info</button>
<div id="userInfo"></div>
document.getElementById('fetchButton').addEventListener('click', () => {
const username = document.getElementById('username').value;
const url = `https://api.github.com/users/${username}`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('User not found');
}
return response.json();
})
.then(data => {
document.getElementById('userInfo').innerHTML = `
<p><strong>Name:</strong> ${data.name}</p>
<p><strong>Public Repos:</strong> ${data.public_repos}</p>
<p><strong>Followers:</strong> ${data.followers}</p>
<img src="${data.avatar_url}" alt="Avatar" width="100" />
`;
})
.catch(error => {
document.getElementById('userInfo').innerHTML = `<p>${error.message}</p>`;
});
});
Download the exercise files or clone them directly from Github git clone https://gist.github.com/c76a7bd0bef66713a9ac.git
Type | Resource | Parameters | Description |
---|---|---|---|
POST | http://hangman-api.herokuapp.com/hangman |
- | Create a new game |
PUT | http://hangman-api.herokuapp.com/hangman |
{ token: game token, letter: guess } |
Guess a letter |
GET | http://hangman-api.herokuapp.com/hangman |
{ token: game token } |
Get solution |
-
Create a new game
-
Issue POST request
-
Update the displayed string on the page and store the token
- Use the hidden field with the class
token
- Use the hidden field with the class
-
Don't allow the user to start a new game, hide the New game bubtton
-
-
Interact with the API to try out different guesses
-
Issue PUT request
- Use
data.correct
to check if the response was successful or not
- Use
-
Update the displayed word
-
Update the stored token
-
Update remaining attempts and display all guesses
- Append each attempt to the
$('.attempts')
using a span - If the attempt is successful, include the class
correct
in the span; if it is unsuccessful, include the classwrong
- You can then find out how many wrong attempts there were using
$('.wrong').length+1;
- Append each attempt to the
-
-
On the 7th failure, retrieve the solution using the GET request
- Display the solution, hide the input field and allow a user to start a new game
-
Bonus don't process numbers, guesses that have already been attempted or empty space
-
You can use jQuery's
$.isNumeric(character))
to check if a letter is a number -
trim()
removes all space around a string. You can applytrim()
and check for the length to make sure the guess is one character long -
All the attempted guesses are already in
.attempts
. You can useindexOf(character)
to check if it's contained in a string. -
Add the class
error
to the letter field when the character is not allowed.
-
- Use
toLowerCase()
for comparing strings asa
is not the same asA
Here is our version of Hangman.
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 and let us know.
Now that you are familiar with HTTP requests, AJAX and APIs, how about you go away and create a webpage that pulls in all instagram pictures with a certain hashtag.
Or embed a google map onto a webpage with it pointing to a destination of your choice in London.