Skip to content

Instantly share code, notes, and snippets.

@DeepNeuralAI
Last active June 13, 2019 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeepNeuralAI/8b6e5e9e4d92001dd66cf13ec0eba5bf to your computer and use it in GitHub Desktop.
Save DeepNeuralAI/8b6e5e9e4d92001dd66cf13ec0eba5bf to your computer and use it in GitHub Desktop.
Server Side API Challenge

Server Side Programming

image

Yesterday, we worked on strictly client side.

Today we are going to work on the server side of things.

This challenge has two phases in Express.js


Phase One:

index.html

- Build a GET endpoint on the server side

- Inside the GET method, write out a response in JSON format
- Perform a GET request in the browser to your server side endpoint
- You should see output like this:

image

create.html

- Build a POST endpoint on the server side

- Store the request data (this will be sent from the client)
- Write out a response in JSON. The output should have a status message, and the request data sent
- Output should look like this:

image


Phase Two:

index_2.html

  • Write a GET endpoint to https://reqres.in/api/users?page=2' on the server side. (This URL should NOT be seen in the browser, or within the script tags.)
   - Write a function client side to pull data from your GET endpoint
   - Format the obtained data and render it in HTML and append to the table.

Output should look like this: image

create_2.html

  • Write a POST endpoint to https://reqres.in/api/users on the server side. (This URL should NOT be seen in the browser, or within the script tags.)

image

- Create two form input fields:
  * Name
  * Job
- Create a Submit button
- Add an event listener to the Submit button
  * Upon submit, obtain the values entered into the Name and Job form fields
  * POST this data to your POST endpoint that you wrote server-side
  * Write out a response on the server side so that you get the following output once the POST is successful:

image

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Users - Index</title>
</head>
<body>
<h3>Show All Users</h3>
<script>
// Make a GET request to your API endpoint
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Create A User</title>
</head>
<body>
<h3>Create a User</h3>
Put Form Fields Here...
<script>
// write out your async calls -- you want to POST data to your API endpoint
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Users - Index</title>
</head>
<body>
<style>
.avatar {
border-radius: 50%;
height: 50px;
}
</style>
<h3>Show All Users</h3>
<table class="table">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Email</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Avatar</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
// Make a GET request to your API
// With that data, format it and inject it into the table above
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>POST to API</title>
</head>
<body>
<h3>Create User to API</h3>
Add Form Fields Here
<script>
// Use the form fields above, and upon click, send that data to your POST endpoint
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<title>Create A User</title>
</head>
<body>
<h3>Create a User</h3>
<label for="email">Email</label><br>
<input type="text" name="email"><br>
<label for="first">First Name</label><br>
<input type="text" name="first"><br>
<label for="last" name="last">Last Name</label><br>
<input type="text" name="last"><br>
<label for="avatar" name="avatar">Avatar</label><br>
<input type="text" name="avatar"><br>
<hr>
<button type="submit" class="btn btn-primary">Create User</button>
<script>
// Without a form
const submitButton = document.querySelector('button');
submitButton.addEventListener('click', () => {
const email = document.querySelector('input[name="email"]').value
const first = document.querySelector('input[name="first"]').value
const last = document.querySelector('input[name="last"]').value
const avatar = document.querySelector('input[name="avatar"]').value
const data = {
email: email,
first: first,
last: last,
avatar: avatar
}
createUser(data);
})
async function createUser_old(data) {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(data)
}
// Old Way
const response = await fetch('/api', options);
const json = await response.json();
console.log(`Status code: ${response.status}`)
console.log("Response sent back from API endpoint:")
console.log(json)
}
async function createUser(data) {
// Better Way
const response = await axios.post('/api', data)
console.log(`Status code: ${response.status}`)
console.log("Response sent back from API endpoint:")
console.log(response.data)
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>POST to API</title>
</head>
<body>
<h3>Create User to API</h3>
<label for="name">Name</label>
<input type="text" name="name">
<label for="job">Job</label>
<input type="text" name="job">
<button type="submit" class="btn btn-primary">Create</button>
<script>
const submit = document.querySelector('button');
submit.addEventListener('click', async(e) => {
const name = document.querySelector('input[name="name"]').value;
const job = document.querySelector('input[name="job"]').value;
const data = { name: name, job: job }
postData(data);
})
async function postData_old(data) {
// Old Way
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}
const response = await fetch('/api', options);
const json = await response.json();
console.log(json)
}
async function postData(data) {
// better way
const response = await axios.post('/api', data);
console.log(response.data.data)
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Users - Index</title>
</head>
<body>
<h3>Show All Users</h3>
<script>
async function getAPI() {
const response = await fetch('/api');
const json = await response.json();
console.log(json);
}
getAPI();
</script>
</body>
</html>
// Build Our Own API Endpoints
const express = require('express');
const app = express();
const fetch = require('node-fetch');
// Defining Server
app.listen(3000, () => console.log('listening at 3000'));
app.use(express.static('public'));
app.use(express.json({limit: '1mb'}));
// Define routes
app.get('/api', (request, response) => {
console.log("Got a GET request for the Index Page");
response.json({
status: 'success',
message: 'GET request received'
})
})
app.post('/api', (request, response) => {
console.log("Sending Request to POST Endpoint")
const data = request.body;
console.log(data)
response.json({
status: 'success',
data: data
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Users - Index</title>
</head>
<body>
<style>
.avatar {
border-radius: 50%;
height: 50px;
}
</style>
<h3>Show All Users</h3>
<table class="table">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Email</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Avatar</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
async function showDataFromAPI() {
const response = await fetch('/api');
const data = await response.json();
const results = data.data;
results.forEach(row => {
const rowString = createRow(row);
document.querySelector('tbody').insertAdjacentHTML('beforeend',rowString);
})
}
const createRow = (row) => {
const htmlString = Object.values(row)
.slice(0, -1)
.map(value => `<td>${value}</td>`).join('')
const img = `<td><img src="${row.avatar}" class="avatar"></td>`;
return htmlString + img;
}
showDataFromAPI();
</script>
</body>
</html>
/* - Use our server side app to get data from 3rd party
- Render obtained data to client side
- POST data to a 3rd party API using server side
*/
const express = require('express');
const app = express();
const fetch = require('node-fetch');
// Defining Server
app.listen(3000, () => console.log('listening at 3000'));
app.use(express.static('public'));
app.use(express.json({limit: '1mb'}));
// Define routes
app.get('/api', async (request, response) => {
console.log("Got a GET request for the Index Page");
const res = await fetch('https://reqres.in/api/users?page=2');
const data = await res.json();
// console.log(data);
response.json({
status: 'GET Request Received',
data: data.data
})
})
app.post('/api', async(request, response) => {
console.log("Sending Request to POST Endpoint")
const data = request.body;
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}
const res = await fetch('https://reqres.in/api/users', options);
const json = await res.json();
response.json({
status: 'success',
data: json
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment