Restfull Api Con Node - Js
Restfull Api Con Node - Js
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
An extremely important aspect of being a modern web developer is
knowing how to work with APIs to facilitate communication between
di erent software systems.
In this tutorial, you’ll learn how to create your own RESTful API in a
Node.js environment running on an Express server and utilizing a
PostgreSQL database.
Prerequisites
In order to get the most out of this tutorial, there are a few
prerequisites:
Goals
By the time you complete this article, you should have a fully
functional API server running on an Express framework in Node.js. The
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
API should be able to handle the HTTP request methods that
correspond to the PostgreSQL database that the API gets its data from.
You will learn how to install PostgreSQL and work with it through the
command line interface.
RESTful APIs most commonly utilize HTTP requests. Four of the most
common HTTP methods are GET , POST , PUT , and DELETE , which are
the methods by which a developer can create a CRUD system – create,
read, update, delete.
PostgreSQL database
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
PostgreSQL, commonly referred to as Postgres, is a free and open
source relational database management system. You might be familiar
with a few other similar database systems, such as MySQL, Microsoft
SQL Server, or MariaDB, which compete with PostgreSQL.
Installation
If you’re using Windows, download a Windows installer of PostgreSQL.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
programs. If you don’t, simply click on the link and follow the
instructions to install Homebrew.
You may see instructions on the web that will say brew install
postgres instead of postgresql . Both of these options will install
If at any point you want to stop the postgresql service, you can run
brew services stop postgresql .
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
PostgreSQL is installed now, so the next step is to connect to the
postgres command line, where we can run SQL commands.
connect you to a PostgreSQL host. Running psql --help will give you
more information about the available options for connecting with
psql .
“your_username”)
--w — --no-password | never prompt for password
automatically)
We’ll just connect to the default postgres database with the default
login information – no option flags.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
psql postgres
You’ll see that we’ve entered into a new connection. We’re now inside
psql in the postgres database. The prompt ends with a # to denote
postgres=#
postgres=# \conninfo
You are connected to database "postgres" as user "your_username"
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
\c | Connect to a new database
Let’s create a new database and user so we’re not using the default
accounts, which have superuser privileges.
Create a user
First, we’ll create a role called me and give it a password of password .
A role can function as a user or a group, so in this case, we’ll be using it
as a user.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
You can run \du to list all roles/users.
me | Create DB | {}
postgres | Superuser, Create role, Create DB | {}
Now we want to create a database from the me user. Exit from the
default session with \q for quit.
postgres=# \q
psql -d postgres -U me
Create a database
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
We can create a database with the SQL command.
postgres=> \c api
You are now connected to database "api" as user "me".
api=>
Create a table
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
The last thing we’ll do in the psql command prompt is create a table
called users with three fields – two VARCHAR types and an auto-
incrementing PRIMARY KEY id.
api=>
CREATE TABLE users (
ID SERIAL PRIMARY KEY,
name VARCHAR(30),
email VARCHAR(30)
);
Make sure not to use the backtick (`) character when creating and
working with tables in PostgreSQL. While backticks are allowed in
MySQL, they’re not valid in PostgreSQL. Also, ensure you do not have a
trailing comma in the CREATE TABLE command.
We’ll add two entries to users to have some data to work with.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Let’s make sure that got added correctly by getting all entries in
users .
Now we have a user, database, table, and some data. We can begin
building our Node.js RESTful API to connect to this data stored in a
PostgreSQL database.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
mkdir node-api-postgres
cd node-api-postgres
You can either run npm init -y to create a package.json , or copy the
code below into a package.json file.
{
"name": "node-api-postgres",
"version": "1.0.0",
"description": "RESTful API with Node.js, Express, and PostgreS
"main": "index.js",
"license": "MIT"
}
We’ll want to install Express for the server and node-postgres (pg) to
be able to connect to PostgreSQL.
npm i express pg
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Now we have our dependencies loaded into node_modules and
package.json .
Create an index.js file, which we’ll use as the entry point for our
server. At the top, we’ll require the express module, built in
bodyParser middleware, and set our app and port variables.
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
We’ll tell a route to look for a GET request on the root ( / ) URL, and
return some JSON.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
app.get('/', (request, response) => {
response.json({ info: 'Node.js, Express, and Postgres API' })
})
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
From the command line, we can start the server by hitting index.js .
node index.js
App running on port 3000.
{
info: "Node.js, Express, and Postgres API"
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
}
The Express server is running now, but it’s only sending some static
JSON data that we created. The next step is to connect to PostgreSQL
from Node.js to be able to make dynamic queries.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
host: 'localhost',
database: 'api',
password: 'password',
port: 5432,
})
The aim of this tutorial is to allow GET , POST , PUT , and DELETE
operations on the API which will run the corresponding database
commands. To do this we’ll set up a route for each endpoint, and a
function to correspond to each query.
Creating routes
We’re going to create six functions for six routes, seen in the chart
below. First, we’ll go through and create all of the functions for each
route, then we’ll export the functions so they’re accessible:
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
GET — / | displayHome()
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
throw error
}
response.status(200).json(results.rows)
})
}
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
}
response.status(200).json(results.rows)
})
}
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
})
}
It is worth noting that PUT is idempotent, meaning the exact same call
can be made over and over and will produce the same result. This is
di erent than POST , in which the exact same call repeated will
continuously make new users with the same data.
pool.query(
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
'UPDATE users SET name = $1, email = $2 WHERE id = $3',
[name, email, id],
(error, results) => {
if (error) {
throw error
}
response.status(200).send(`User modified with ID: ${id}`)
}
)
}
DELETE a user
Finally, we’ll use the DELETE clause on /users/:id to delete a specific
user by id. This call is very similar to our getUserById() function.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
}
response.status(200).send(`User deleted with ID: ${id}`)
})
}
Export
In order to access these functions from index.js , we’ll need to export
them. We can do this with module.exports , creating an object of
functions. Since we’re using ES6 syntax, we can write getUsers
instead of getUsers:getUsers , and so on.
module.exports = {
getUsers,
getUserById,
createUser,
updateUser,
deleteUser,
}
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
const Pool = require('pg').Pool
const pool = new Pool({
user: 'me',
host: 'localhost',
database: 'api',
password: 'password',
port: 5432,
})
const getUsers = (request, response) => {
pool.query('SELECT * FROM users ORDER BY id ASC', (error, res
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
functions we created.
To get all the exported functions from queries.js , we’ll require the
file and assign it to a variable.
const db = require('./queries')
Now for each endpoint, we’ll set the HTTP request method, the
endpoint URL path, and the relevant function.
app.get('/users', db.getUsers)
app.get('/users/:id', db.getUserById)
app.post('/users', db.createUser)
app.put('/users/:id', db.updateUser)
app.delete('/users/:id', db.deleteUser)
Here is our complete index.js , the entry point of the API server.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
const app = express()
const db = require('./queries')
const port = 3000
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
Now with just these two files, we have a server, database, and API all
set up. You can start up the server by hitting index.js again.
node index.js
App running on port 3000.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Now if you go to http://localhost:3000/users or
http://localhost:3000/users/1 , you’ll see the JSON response of the
two GET requests. But how can we test our POST , PUT , and DELETE
requests?
This can be done with curl, a command line tool that’s already
available on your terminal. Below are examples you can run on the
command line to test all of the protocols.
Make sure that the server is actively running in one Terminal window
while you run these commands in a separate window.
POST
Add a new user with the name Elaine and email elaine@example.com.
PUT
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Update the user with id 1 to have the name Kramer and email
kramer@example.com.
DELETE
Delete the user with id 1 .
Conclusion
Congratulations, you should now have a functioning API server
running on Node.js and hooked up to an active PostgreSQL database. In
this tutorial, we learned how to install and set up PostgreSQL in the
command line, how to create users, databases, and tables, and how to
run SQL commands. We also learned how to create an Express server
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
that can handle multiple HTTP methods, and how to use the pg
module to connect to PostgreSQL from Node.
With this knowledge, you should be able to build on this API and utilize
it for your own personal or professional development projects.
Share this:
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
#node #postgresql
The best Rust frameworks to Rust for front-end developers Understanding lazy loading in
check out in 2019 JavaScript
Obinna Ekwuno
Obinna Ekwuno Oct 17, 2019 · 6 min read Alexander Nnakwue
Oct 18, 2019 · 5 min read Oct 17, 2019 · 6 min read
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
June 10, 2019 at 10:56 pm
Can you make a tutorial of user registration using react native with the
PostgreSQL and inserting the data with the button onPress function , what i
mean is a restful api with node.js using react native with the PostgreSQL and
just add new user into database….
Thanks
Thanks for this tutorial. I was getting an error like “Cannot GET /users” and the
resolution was to stop and start node index.js – in case anyone else gets stuck
on that
I don’t really know why this brilliant tutorial doesn’t have many likes or
comments. It’s perfect for a Node newbie looking to intercept the postgres
world to build apis. Thanks very much!!
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Vicky Says: Reply
June 25, 2019 at 10:06 am
This was incredible. Thank you so much. I’ve been having so many issues
connecting to postgres that I thought it was going to take me forever to connect
locally as well.
Note to anybody who might have permission issues connecting with your
created user, you might have to grant read access instead of just creating a
database: https://dba.stackexchange.com/questions/36870/permission-
denied-in-postgres
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
July 2, 2019 at 10:28 pm
absolutely nice starting guide for me, theres a bit mistype in your create user
response, just change to “results” and you good to go, anyway thanks… your
starting guide helps me understand node works
RS Says: Reply
July 21, 2019 at 8:45 am
Real good
Great tutorial. Just a note, some of the Github examples are blank
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Artemis Says: Reply
July 30, 2019 at 10:59 am
Thanks for the tutorial, this was really helpful getting me started on making a
backend for my apps
I had only one issue, the setup with the bodyParser middleware (`app.use()`
lines) was preventing my browser from connecting to Express. The server
would start via CLI fine, but I was getting “waiting for localhost” when trying
to hit the server from Firefox & Chrome. Starting Express in debug mode didn’t
show anything indicative.. But after removing those lines, the rest of the
tutorial worked fine! I’m going to investigate what the bodyParser component
is meant for because it’s likely I’m skipping something important
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Awesome tutorial. Real help for beginners. With your step by step approach you
explained everything so clearly. Thanks!
Hello there !
I got through the whole tutorial (which is really clear and great, thanks for that
!), and I guess this is going to be a pretty stupid question (fairly new to
Node/Express/APIs), but I’m on Windows, and the curls commands to POST
and UPDATE don’t work, only the DELETE one those.
When I try, it returns an error :
“Cannot destructure property `name` of undefined or null;”
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Ali G Says: Reply
August 23, 2019 at 10:08 am
@ryan this means that you are trying to access name from a variable which is
undefined
request.body is undefined and you are trying to get the name data which will
throw this error
G Says: Reply
September 3, 2019 at 10:46 am
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Thanks for this article. Helped a novice like me to start on Nodejs and PostGres.
As token of thanks…was getting undefined for results.insertId for insert POST
api. I replaced that by response.status(201).send(`User added with ID:
${results.rows[0].id}`) to get the last inserted id.
One of the best tutorials I have ever seen on the internet world! Great job~
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Leave a Reply
We just moved our blog! Does something seem off? Email support@logrocket.com
Search... >
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD