CRUD REST API Example - how to build a complete CRUD REST API with Node.js and codehooks.io
This comprehensive tutorial shows you how to build a complete CRUD (Create, Read, Update, Delete) REST API from scratch. You'll learn how to implement all essential database operations through a RESTful interface, with working example code that you can run immediately.
This CRUD REST API example demonstrates:
- Full database CRUD operations (Create, Read, Update, Delete)
- RESTful endpoint implementation
- Query parameter handling
- NoSQL database integration
- Error handling
- Production-ready code structure
The CRUD REST API example lets clients access your data, e.g.
- Search database with url query strings, e.g.
GET
/dev/customer?name=Bill&city=Berlin
- Get object by ID, e.g.
GET
/dev/customer/17f7990aa6d-w84jerq77u7w3d
- Create new objects from JSON data, e.g.
POST
/dev/customer
{JSON}
Automate the creating of a CRUD REST API with the open source library Crudlify.
Read more about how to about how to automate the development and deployment of CRUD REST API's in this blog post.
Project Structure for the CRUD REST API Example
The project has one main JavaScript file (index.js) and four JavaScript library files: create.js, read.js, update.js and delete.js.
- Create a project with the
coho create
CLI command. - Change to the project directory and install
npm i query-to-mongo codehooks-js -s
. - Delete default index.js file and create new files
touch index.js create.js read.js delete.js update.js
- Open code files in your favorite code editor and enter the follwing code.
CRUD REST API Example: Main function (index.js)
The index.js file defines the HTTP routes (routehooks) for the serverless functions. The functions are implemented as separate code files for clarity and better organisation of the project.
import app from 'codehooks-js';
// import libraries from separate files
import { createFunc } from './create';
import { readOneFunc, readManyFunc } from './read';
import { deleteFunc } from './delete';
import { updateFunc } from './update';
// Codehooks API routes for the CRUD REST API example
app.post('/:collection', createFunc);
app.get('/:collection', readManyFunc);
app.get('/:collection/:ID', readOneFunc);
app.put('/:collection/:ID', updateFunc);
app.delete('/:collection/:ID', deleteFunc);
export default app.init();
Create function (create.js)
import { Datastore } from 'codehooks-js';
export async function createFunc(req, res) {
const { collection } = req.params;
const document = req.body;
const conn = await Datastore.open();
const result = await conn.insertOne(collection, document);
res.json(result);
}
Read function (read.js)
// use npm package to convert URL query string to MongoDB query filter
const q2m = require('query-to-mongo');
import { Datastore } from 'codehooks-js';
export async function readManyFunc(req, res) {
const { collection } = req.params;
const conn = await Datastore.open();
const options = {
filter: q2m(req.query).criteria,
};
conn.getMany(collection, options).json(res);
}
export async function readOneFunc(req, res) {
const { collection, ID } = req.params;
const conn = await Datastore.open();
try {
const result = await conn.getOne(collection, ID);
res.json(result);
} catch (e) {
res
.status(404) // not found
.end(e);
}
}
Update function (update.js)
import { Datastore } from 'codehooks-js';
export async function updateFunc(req, res) {
const { collection, ID } = req.params;
const document = req.body;
const conn = await Datastore.open();
const result = await conn.updateOne(collection, ID, document, {});
res.json(result);
}
Delete function (delete.js)
import { Datastore } from 'codehooks-js';
export async function deleteFunc(req, res) {
const { collection, ID } = req.params;
const conn = await Datastore.open();
const result = await conn.removeOne(collection, ID, {});
res.json(result);
}
Deploying the CRUD REST API Example
You can deploy the code with this CLI command:
coho deploy
Testing the deployed CRUD REST API Example
Test your deployed CRUD REST API with curl or Postman (recommended).
Use the CLI command coho info
to see API tokens for the project datastore.
POST
curl --location --request POST 'https://<YOUR_PROJECT_ID>.api.codehooks.io/dev/customer' \
--header 'x-apikey: <YOUR_API_TOKEN>' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Bill",
"email": "[email protected]"
}'
{"name":"Billy Bob","email":"[email protected]","_id":"640f60e2b4fdc00015c4280f"
PUT
curl --location --request PUT 'https://<YOUR_PROJECT_ID>.api.codehooks.io/dev/customer/640f60e2b4fdc00015c4280f' \
--header 'x-apikey: <YOUR_API_TOKEN>' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Billybob"
}'
{
"name": "Billybob",
"email": "[email protected]",
"_id": "640f60e2b4fdc00015c4280f"
}
GET (all)
curl --location --request GET 'https://<YOUR_PROJECT_ID>.api.codehooks.io/dev/customer' \
--header 'x-apikey: <YOUR_API_TOKEN>'
{
"name": "Billybob",
"email": "[email protected]",
"_id": "640f60e2b4fdc00015c4280f"
}
...
GET (by query)
curl --location --request GET 'https://<YOUR_PROJECT_ID>.api.codehooks.io/dev/[email protected]' \
--header 'x-apikey: <YOUR_API_TOKEN>'
{
"name": "Billybob",
"email": "[email protected]",
"_id": "640f60e2b4fdc00015c4280f"
}
DELETE
curl --location --request DELETE 'https://<YOUR_PROJECT_ID>.api.codehooks.io/dev/customer/640f60e2b4fdc00015c4280f' \
--header 'x-apikey: <YOUR_API_TOKEN>'
{
"_id": "640f60e2b4fdc00015c4280f"
}