Create an API and Resolve them
Ever Wondering why API Created ? Perhaps this is the right topic for you to get started
Oh hey , before to get started , you may that wanted to practice and learning , here a repo for you to practice
What Will You Know
Middleware and Accesbility
- Objective : Build an API and Get the Data
- Method : API and Accessbility
- Library : Node.Express
What is API ?
- API is Standfor Application Program Interface
- It used to allows two applications to connect with each other.
- An Example is a Facebook UI , is the front-end .
And the thing that save your history chat , log or something will be required a backend or Database .
The API will take care as the bridge between them.
API vs REST(ful) API ?
- REST is standfor Representational State Transfer.
- REST API is an API , but with strict configuration .
- It means , you only can access the data within their parameter .
- An API is just the method name .
Why REST API created ?
- The goals is that you can bring all the data as long as you has an internet .
- It means that you no need to worry about the platform anymore .
- One Data multiple platform .
- Like Facebook Can be accessed on Browser , Android , Iphone , Smart TV , Amazon Alexa , Smarthouse , Voice Assistant , Smartwatch, Even a Refrigator
Where is API used ?
an API will be used as bridge between front-end and back-end , But you can say that an API is a part of Server-side (A.K.A Backend)
A Things about API
API is special that can allowed you change the data overtime . Here the list what can API do .
- GET || Retrieve information about the REST API resource
- POST || Create a REST API resource
- PUT || Update a REST API resource
- DELETE || Delete a REST API resource or related component
Prequisite
Lib : Node JS and Express
$ npm initentry point: (index.js)$ npm install express --savego to localhost:3000
Let’s start make an API !
The Plan :
- We will be Build some API that contain the information about books and hotel.
- We will created the notice if succesful
- We will created the error boundary if failed to run .
- Final . WE are ready to deploy our API to the cloud !
Entry Section
- It will be the entry point that will be handled
index.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");const app = express();
const PORT = process.env.PORT || "3000";const booksRoute = require("./api/books");
const hotelsRoute = require("./api/hotels");// Use middleware
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());// Handle http requests
app.get("/", (req, res) => {
return res.send("Requesting API On Standby"); {/* This will given the notice when everything success */}
});// Add additional routes
app.use("/books", booksRoute);
app.use("/hotels", hotelsRoute);// Start the server
app.listen(PORT, () => console.log(`Running on port ${PORT}`));exports = module.exports = app;
Middleware Section
It’s where the object will be called
books.js
const express = require("express");
const router = express.Router();
const fs = require("fs");// to string . or stringify
const booksData = JSON.parse(
fs.readFileSync("./api/booksData.json").toString()
);
// const booksData = JSON.parserequire('./api/booksData.js')// define the home page route
router.get("/", function (req, res) {
res.json(booksData);
});router.get("/:bookId", (req, res) => {
console.log(`Looking for data ${req.params.bookId}`);
const book = booksData.filter((item) => {
return item.card === req.params.bookId;
});
if (book != "") {
res.send(book);
} else {
res.status(404).send("Book not found");
}
});// params
router.get("/title/:query", (req, res) => {
// TODO urldecode query
const books = booksData.filter((item) => {
return item.title.toLowerCase().includes(req.params.query.toLowerCase());
}); if (books.length > 0) {
res.send(books);
} else {
res.status(400).send("No Results");
}
});// define the about route
router.get("/about", function (req, res) {
res.send("About Books");
});module.exports = router;
Data Section
It’s an Object , you can fill anything but you might need an interactive state like GET and DELETE
booksData.json
[
{
"card": "9781593275846",
"title": "test1",
"subtitle": "",
"nama": "name1",
"hari": "Day",
"lokasi": "Indonesia",
"waktu": "18.00-20.00",
"description": "",
"infoLink": "website description",
"url": "website"
},
{
"card": "9781593275846",
"title": "test1",
"subtitle": "",
"nama": "name1",
"hari": "Day",
"lokasi": "Indonesia",
"waktu": "18.00-20.00",
"description": "",
"infoLink": "website description",
"url": "website"
}
]
Why is it Work ?
- The important thing on API is about Data , Middleware (Request/Response)
Troubleshooter
Possible things :
- Port
var port = process.env.PORT || 3000;
- Parameter
router.get("/", function (req, res) {
res.json(booksData);
});
- Middleware
var express = require('express')
var app = express()app.get('/', function (req, res) {
res.send('Hello World from Backend !')
})app.listen(3000)
Conclusion
Making an API through Backend like Express can be so trivia , it can be easy or a nightmare
But not to worry , the community will be there for you . If not you can talk with leader or the team that you can depends on .
So Congratulations for making an API~!