Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Lakshyaraj Dash
Lakshyaraj Dash

Posted on

     

Create a rest api using expressjs and postgresql

Hello world! In this article we will learn how to create a rest api using postgresql and expressjs. We will use javascript for this project.

First let us know what are the pre-requisites for this project:-
One must have:

  1. the basic knowledge of javascript and nodejs
  2. must be familiar with basic crud operations
  3. must be familiar with sql commands
  4. must have a basic knowledge of expressjs

Useful links

  1. https://nodejs.dev/en/learn/
  2. https://www.postgresql.org/docs/current/sql-commands.html
  3. http://expressjs.com/

Installer links

  1. NodeJS:https://nodejs.org/en/download/
  2. Postgresql:https://www.postgresql.org/download/

First we will initialize the project folder with a "package.json".

npminit-y
Enter fullscreen modeExit fullscreen mode

Then we will install express, cors (for allowing cross origin requests) & pg (to connect to postgresql).

npmiexpresscorspg
Enter fullscreen modeExit fullscreen mode

Then we will install nodemon as a dev dependency to reload our server automatically.
Do not use nodemon in production servers

npmi-Dnodemon
Enter fullscreen modeExit fullscreen mode

Before connecting to database, we will first create the database

  • Create a database and name it of your own choice.

Create a new database

  • Then go into the schemas and right click on tables. Give a name of "blogs" to your table.

Create a new table named blogs

  • Create the specified columns for the table

Create the specified colums for the table


Create a file "db.js", where we will connect to the database

const{Pool}=require('pg');constpool=newPool({host:'localhost',user:'username',password:'password',port:5432,database:'db_name'})module.exports=pool;
Enter fullscreen modeExit fullscreen mode

Now let's create a folder called routes and create a file "blog.js" inside it.

Then make the required imports

constexpress=require('express');constrouter=express.Router();constpool=require('../db');
Enter fullscreen modeExit fullscreen mode

The first api route will be to query all the blogs from the database. We will usepool.query('') to run our sql commands.

router.get('/',async(req,res)=>{letblogs=awaitpool.query('SELECT * FROM blogs ORDER BY blogs.timestamp ASC');// Order posts by ascending orderres.status(200).json({status:200,totalResults:blogs.rowCount,blogs:blogs.rows});})
Enter fullscreen modeExit fullscreen mode

Then the second api route will be to query a specific blog from the database.

router.get('/:slug',async(req,res)=>{letblog=awaitpool.query(`SELECT * FROM blogs WHERE slug='${req.params.slug}'`);if(blog.rowCount===0){res.status(404).json({status:404,message:'No such blog was found!'});}else{res.status(200).json({status:200,blog:blog.rows});}})
Enter fullscreen modeExit fullscreen mode

Then the third api route will be to add a blog to the database the database.

router.post('/addblog',async(req,res)=>{const{title,tagline,slug,description}=req.body;letsaveBlog=awaitpool.query(`INSERT INTO blogs (title, tagline, slug, description) VALUES ('${title}', '${tagline}', '${slug}', '${description}')`);if(!saveBlog){res.status(404).json({status:404,message:'Some error occurred! Cannot save blog :('});}else{res.status(200).json({status:200,messaeg:'Your blogpost has been added successfully!'});}})
Enter fullscreen modeExit fullscreen mode

Then the fourth api route will be to update a specific blog in the database.

router.put('/updateblog/:slug',async(req,res)=>{const{title,tagline,slug,description}=req.body;letsaveBlog=awaitpool.query(`UPDATE blogs SET title='${title}', tagline='${tagline}', slug='${slug}', description='${description}' WHERE slug='${req.params.slug}'`);if(!saveBlog){res.status(404).json({status:404,message:'Some error occurred! Cannot update blog :('});}else{res.status(200).json({status:200,messaeg:'Your blogpost has been updated successfully!'});}})
Enter fullscreen modeExit fullscreen mode

Then the fourth api route will be to delete a specific blog from the database.

router.delete('/deleteblog/:slug',async(req,res)=>{letsaveBlog=awaitpool.query(`DELETE FROM blogs WHERE slug='${req.params.slug}'`);if(!saveBlog){res.status(404).json({status:404,message:'Some error occurred! Cannot delete blog :('});}else{res.status(200).json({status:200,messaeg:'Your blogpost has been deleted successfully!'});}})
Enter fullscreen modeExit fullscreen mode

Then we will export the router module

module.exports=router;
Enter fullscreen modeExit fullscreen mode

Create a "index.js" file to handle all the api routes.
Make the necessary imports

constexpress=require('express');constcors=require('cors');constapp=express();// initialization of express with appconstport=5000;
Enter fullscreen modeExit fullscreen mode

Then write these two lines of code

app.use(cors());// enable cross origin requestsapp.use(express.json());// use default json body parser to parse the data.
Enter fullscreen modeExit fullscreen mode

Use the api routes

app.use('/api/blogs',require('./routes/blog'))
Enter fullscreen modeExit fullscreen mode

Create a custom 404 message

app.use((req,res,next)=>{res.status(404).json({status:404,message:'No such route was found! Please go to /api/blogs.'});})
Enter fullscreen modeExit fullscreen mode

Listen on the given port

app.listen(port,()=>{console.log(`RestAPI listening on http://localhost:${port}`)})
Enter fullscreen modeExit fullscreen mode

Yay! You have successfully created your rest api.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a programmer in python and I build many basic projects in python. I like to develop the website backend with python. Link to my github profile: https://github.com/codewithlaksh/
  • Joined

More fromLakshyaraj Dash

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp