The goal of this sample to is get started with REST from client side.
We will get as starting point an application that displays a list of harcoded items.
-
Start with the starting implementation that is located under the folder 00_start.
-
Let's install the needed dependencies.
npm install
- And start the application to check that everything is working as expected.
npm start
- If we check the current implementation we are getting a list of harcoded data. The related
service
that provides data can be found in src/API/carsApi.double.js
const data = [
{
"car_id": 1,
"name": "ABX",
"brand": "Tokiota",
"year_release": "1999"
},
{
"car_id": 2,
"name": "AZE",
"brand": "Tokiota",
"year_release": "1995"
},
];
export const getAllCars = () => {
return new Promise((resolve, _) => {
setTimeout(() => {
const cars = data.map((i) => i);
resolve(cars);
}, 500);
});
}
export const getCarById = (id) => {
return new Promise((resolve, _) => {
setTimeout(() => {
const car = data.map((i) => i)
.find((c) => c.car_id === id);
resolve(car);
}, 500);
});
}
export const addCar = (car) => {
return new Promise((resolve, _) => {
setTimeout(() => {
car['car_id'] = (data.length + 1);
data.push(car);
resolve('ok');
}, 500);
});
};
-
Edit src/API/carsApi.js to implent functions above with axios or native fetch or XMLHttpRequest
-
Hints:
- Copy and paste the double functions into src/API/carsApi.js, this way yo already have the right signatures.
- Start implementation with getAllCars(), follow with getCarById(id), and for last addCar(car).
- getAllCars() url: 'http://localhost:3050/api/cars'.
- getAllCarById(2) url: 'http://localhost:3050/api/cars/2'.
- addCar url: 'http://localhost:3050/api/cars'.
POST
http verb.
-
Start server:
- On server folder as root in bash terminal
npm install
- Run server
npm start
- Check that server is running by pasting this url on browser:http://localhost:3050/api/cars
- As optional part implement in more than one way the real API.
- Create security layer for API requests. Note, for implement security layer you have to implement as well the authentication server.
- Modify current server and client to work with GraphQL.
We are an innovating team of Javascript experts, passionate about turning your ideas into robust products.
Basefactor, consultancy by Lemoncode provides consultancy and coaching services.
Lemoncode provides training services.