Thinc. First Code Backend (Part II: Express.js)
In Part I, we learn the core concept of APIs. Now it’s time to actually make those APIs. In this tutorial, we are going to use Javascript + Express.js to create APIs server.
If you have not read part I yet, follow this link.
The time to take a step has come…
Keep calm, and follow the instruction. =v=
Programs needed: NodeJS, VScode
Part 1: Setting up
- Make sure that VSCode and NodeJS are downloaded and installed properly
- Download zip file from https://github.com/himkwtn/thinc-first-code-freshmen and extract (or clone the project if you have git)
- Open the folder with VScode
- Open the integrated terminal and install dependencies with the following command:
npm install
Part 2: Basic Syntax
Navigate to hello-world.js
for reference
- variable declaration use
let
if the value may be changed later
let a = 5; // a = 5
a = a + 5; // now a = 10
use const
for variable whose value will not be changed
const PI = 3.15; // PI = 3.14
PI = 3; // error because PI can not be changed
2. Printing: use console.log
console.log("Hello World"); // will print "Hello World" to terminal const number = 42; console.log(number); // will print 42
3. Data Type
- number: 1, 2, 3.456
- string: text ex.
'Hello World'
both single and double quote can be used
"Hello World"
'Hello World'
- boolean:
true/false
- array: list of multiple variables
let numbers = [1, 1, 2, 3, 5, 8];
let teletubbies = ["tinky winky", "dipsy", "lala", "poe"]; // to access the value, use index console.log(numbers[2]); // will print 2. console.log(teletubbies[0]); // will print "tinky winky"
// Note that the first index is zero
- object: key-value pair.
let human = {
first_name: "John",
last_name:"Doe",
age:20
}; // to access value, use the key Example:
console.log(human.first_name); // will print "John" // can be nested let anotherHuman = {
name: "Manud",
address: {
country: "Thailand",
province: "Bangkok"
},
friends: [
"Cat",
"Dog",
"Bird"
]
};
console.log(anotherHuman.address.country); // will print "Thailand"
4. Functions: accept input(s), do something with that input(s) and may return some value
function greeting (name) {
console.log("Hello " + name);
}
function add (num1, num2) {
return num1 + num2 ;
} greeting("World!"); // will print "Hello World!"
const num3 = add(1,2);
console.log(num3); // will print 3
Part 3: Backend Activity
3.1: “ Hello World!”
- In the terminal, type
npm start
2. Go to any web browser and type localhost:3000 into the url
3. Click the Click Me button!
4. Go to file routes/api.js
and find the lines
router.get("/hello-world", (req, res) => {
const response = "Hello World!";
res.send(response);
});
4. Try changing the value of response and see what happens.
3.2 GET / POST Request
- GET Request: sends data via URL
Query
- Example: a request is sent to the url
/find-user?id=5
?id=5
is the query- to use this data, use
req.query.<variable-name>
req = { // stuff
query:{
id: "5"
}
} router.get("/find-user", (req, res) => {
const id = req.query.id;
const user = findUserById(id)
res.send(user);
});
- multiple variables is possible
?id=5&age=20&city=Bangkok
Parameters (Note that it can also be used with POST request)
- Example: a request is sent to the url
/find-user/5
/5
is the params- to use this data, use
req.params.<params-name>
req = { // stuff params:{
id: "5"
}
} router.get("/find-user/:id", (req, res) => {
const id = req.params.id;
const user = findUserById(id)
res.send(user);
});
2. POST Request: sends data via http body in JSON (JavaScript Object Notation) format, can not be seen on URL
- Example: login data sent to url
/login
{
"username": "Abcd",
"password": "1234"
}
- to use this data, use
req.body.<key>
req = {
// stuff
body:{
username: "Abcd",
password: "1234"
}
} router.post("/login", (req, res) => {
const username = req.body.username;
const password = req.body.password;
// do authentication stuff
res.send("welcome!");
});
Try each type of request in routes/api.js
in these routes
router.get("/get", (req, res) => {
res.send();
});
router.get("/params/:params", (req, res) => {
res.send();
});
router.post("/post", (req, res) => {
res.send();
});
3.3 Basic CRUD Operations
Go to the file routes/api.js
and complete the code for each routes
router.post("/students/create", (req, res) => {
res.send();
});
router.get("/students/read/:id", (req, res) => {
res.send();
});
router.post("/students/update/:id", (req, res) => {
res.send();
});
router.get("/students/delete", (req, res) => {
res.send();
});
Create
- POST Request to
/api/students/create
with the following body
{
"name" : name,
"faculty" faculty,
"contact": {
"phone": phone,
"email": email,
"line": line
}
}
- function
createStudent
accepts astudent
(object), create a new student and return that student
Read
- GET Request to
/api/students/read/:id
with id as parameter - function findStudent accepts
id
and return the student with thatid
Update
- POST Request to
/api/students/update/:id
with id as parameter and the following the body
{
"subjects": [
subject1,
subject2,
subject3,
…
]
}
- function
updateStudent
acceptsid
and subjects array, update the student with thatid
and return the updated student
Delete
- GET Request to
/api/students/delete
withid
as query - function
deleteStudent
acceptsid
, delete the student with thatid
and return the deleted student