Basic rest api overview
To install an express application, run the following in a new directory by
npm install express-generator -g
Running the generator, a basic application can be generated by:
express --view=pug myapp
for further build options run:
express -h
To run the application, cd to the location and use:
npm start
CRUD:
- Creation - post
- Read - get
- Update - put
- Delete - delete
However, http protocols do not directly translate, as post may be used to also read - post can be used for creation and reading but data or a data set does not need to be returned. For example, validating a user login does not need to return any data other than that the login attempt is either successful or if it has failed.
Basic express application can be made in the routes folder, by doing the follows:
router.get('/get', function (req, res) {
res.send('Hello World!')
})
Queries can be defined as follows:
router.get('/login?username=testuser&password=testpass', function (req, res) {
res.send(`a request for the user: ${req.query.username} and password: ${req.query.password} has been made`)
})
This allows you to pass a query in the uri as such localhost:8080//login?username=<USER>&pass=<PASS>
Parameters can be defined as follows:
router.get('/book/:bookid', function (req, res) {
res.send(`a request for book ${req.params.bookid} has been made`)
})
Any value passed after book/ will be passed to req.params.bookid, for example localhost:8080//book/29, req.params.bookid will be equivalent to 29
It is useful to understand the entire response and request parameters, which can be logged in the console by printing req or res, such as:
router.get('/', function (req, res) {
console.log(req);
console.log(res);
res.send("request and response logged to the api console");
})
Further documentation can be found at: ExpressJS