A simple Nodejs project, with three major functionalities -
- Authentication
- Authorization
- CRUD operations
git clone https://github.com/alokpaidalwar/nodejs-api-example.git
cd nodejs-api-example
npm install
Add mongodb url
and jwt secret
in .env file
To run your site locally, use:
npm run dev
To run as production, use:
npm run start
This is a mock authentication so you can pass in any username or password to login.
- Set the request to POST and the url to /api/login.
- In the Body for the Postman request, select x-www-form-urlencoded.
- Set two 2 keys- Set the
username
key to any name forstudent
role and 'admin' foradmin
role. Setpassword
to anything. - Hit
Send
. You will get the token, role and username:
A. GET all posts by pagination
- Set the request to GET and the url to /api/post.
- Pass two query parameters page & perPage. Eg
localhost:3000/api/post?page=1&perPage=3
- Since this is a secure route, for testing, you will have to set the token in the
Header
. Set key astoken
and value as token you received from Authentication.
B. GET a post by id
- Set the request to GET and the url to /api/post/:id.
- Url Example
localhost:3000/api/post/61da4fd87e3fc45e78cfd95f
- Since this is a secure route, for testing, you will have to set the token in the
Header
. Set key astoken
and value as token you received from Authentication.
C. Create a post
- Set the request to POST and the url to /api/post.
- In the Body for the Postman request, select x-www-form-urlencoded.
- Set the key
title
to create post with title. Eg.
{ "title": "my first post"}
- Since this is a secure route, for testing, you will have to set the token in the
Header
. Set key astoken
and value as token you received from Authentication.
D. Update a post
- Set the request to PATCH and the url to /api/post/:id.
- In the Body for the Postman request, select x-www-form-urlencoded.
- Set the key
title
to create post with title. Eg.
{ "title": "my updated first post"}
- Url Example
localhost:3000/api/post/61da4fd87e3fc45e78cfd95f
- Since this is a secure route, for testing, you will have to set the token in the
Header
. Set key astoken
and value as token you received from Authentication.
E. Delete a post
- Set the request to DELETE and the url to /api/post/:id.
- Url Example
localhost:3000/api/post/61da4fd87e3fc45e78cfd95f
- Since this is a secure route, for testing, you will have to set the token in the
Header
. Set key astoken
and value as token you received from Authentication.
Run npm test
from the application's root directory.