Set Up an Categorical API Server in Node.js
Within the earlier tutorial, we realized what the REST structure is, the six guiding constraints of REST, how you can perceive HTTP request strategies and their response codes, and the anatomy of a RESTful API endpoint.
On this tutorial, we’ll arrange a server for our API to dwell on. You may construct an API with any programming language and server software program, however we are going to use Node.js, which is the back-end implementation of JavaScript, and Categorical, a preferred, minimal framework for Node.
Set up
Our first prerequisite is ensuring Node.js and npm are put in globally on the pc. We will take a look at each utilizing the -v
flag, which is able to show the model. Open up your command immediate and kind the next.
node -v && npm -v
v10.8.0 6.2.0
Your variations could also be barely completely different than mine, however so long as each are there, we are able to get began.
Let’s create a undertaking listing known as express-api
and transfer to it.
mkdir express-api && cd express-api
Now that we’re in our new listing, we are able to initialize our undertaking with the init command.
npm init
This command will immediate you to reply some questions in regards to the undertaking, which you’ll select to fill out or not. As soon as the setup is full, you will have a package deal.json file that appears like this:
{ "identify": "express-api", "model": "1.0.0", "description": "Node.js and Categorical REST API", "predominant": "index.js", "scripts": { "take a look at": "echo "Error: no take a look at specified" && exit 1" }, "creator": "Tania Rascia", "license": "MIT" }
Now that we have now our package deal.json, we are able to set up the dependencies required for our undertaking. Happily we do not require too many dependencies, simply these 4 listed beneath.
- body-parser: Physique parsing middleware.
- specific: A minimalist net framework we’ll use for our server.
- mysql: A MySQL driver.
- request (non-compulsory): A easy solution to make HTTP calls.
We’ll use the set up
command adopted by every dependency to complete organising our undertaking.
npm set up body-parser specific mysql request
This can create a package-lock.json file and a node_modules listing, and our package deal.json can be up to date to look one thing like this:
{ "identify": "express-api", "model": "1.0.0", "description": "Node.js and Categorical REST API", "predominant": "index.js", "scripts": { "take a look at": "echo "Error: no take a look at specified" && exit 1" }, "creator": "Tania Rascia", "license": "MIT", "dependencies": { "dependencies": { "body-parser": "^1.18.3", "specific": "^4.16.3", "mysql": "^2.16.0", "request": "^2.88.0" } }
Setting Up an HTTP Server
Earlier than we get began on organising an Categorical server, we are going to rapidly arrange an HTTP server with Node’s built-in http
module, to get an thought of how a easy server works.
Create a file known as hello-server.js. Load within the http
module, set a port quantity (I selected 3001
), and create the server with the createServer()
technique.
// Construct a server with Node's HTTP module const http = require('http'); const port = 3001; const server = http.createServer();
Within the introductory REST article, we mentioned what requests and responses are almost about an HTTP server. We’ll set our server to deal with a request and show the URL requested on the server facet, and show a Good day, server! message to the consumer on the response facet.
server.on('request', (request, response) => { console.log(`URL: ${request.url}`); response.finish('Good day, server!') })
Lastly, we are going to inform the server which port to hear on, and show an error if there’s one.
// Begin the server server.hear(port, (error) => { if (error) return console.log(`Error: ${error}`); console.log(`Server is listening on port ${port}`) })
Now, we are able to begin our server with node
adopted by the filename.
node hello-server.js
You will notice this response within the terminal:
Server is listening on port 3001
To test that the server is definitely operating, go to https://localhost:3001/
in your browser’s deal with bar. If all is working correctly, it’s best to see Good day, server! on the web page. In your terminal, you will additionally see the URLs that had been requested.
URL: / URL: /favicon.ico
In the event you had been to navigate to http://localhost:3001/hi there
, you’d see URL: /hi there
.
We will additionally use cURL on our native server, which is able to present us the precise headers and physique which are being returned.
curl -i http://localhost:3001
HTTP/1.1 200 OK Date: Wed, 15 Aug 2018 22:14:23 GMT Connection: keep-alive Content material-Size: 14 Good day, server!
In the event you shut the terminal window at any time, the server will go away.
Now that we have now an thought of how the server, request, and response all work collectively, we are able to rewrite this in Categorical, which has a good less complicated interface and prolonged options.
Setting Up an Categorical Server
We’ll create a brand new file, app.js, which would be the entry level to our precise undertaking. Similar to with the unique http server, we’ll require a module and set a port to begin.
Create an app.js file and put the next code in it.
// Require packages and set the port const specific = require('specific'); const port = 3002; const app = specific();
Now, as a substitute of searching for all requests, we are going to explicitly state that we’re searching for a GET
request on the basis of the server (/
). When /
receives a request, we are going to show the URL requested and the “Good day, Server!” message.
app.get('/', (request, response) => { console.log(`URL: ${request.url}`); response.ship('Good day, Server!'); });
Lastly, we’ll begin the server on port 3002
with the hear()
technique.
// Begin the server const server = app.hear(port, (error) => { if (error) return console.log(`Error: ${error}`); console.log(`Server listening on port ${server.deal with().port}`); });
We will begin the server with node app.js
as we did earlier than, however we are able to additionally modify the scripts
property in our package deal.json file to routinely run this particular command.
"scripts": { "begin": "node app.js" },
Now we are able to use npm begin
to begin the server, and we’ll see our server message within the terminal.
Server listening on port 3002
If we run a curl -i
on the URL, we are going to see that it’s powered by Categorical now, and there are some extra headers comparable to Content material-Kind
.
curl -i http://localhost:3002
HTTP/1.1 200 OK X-Powered-By: Categorical Content material-Kind: textual content/html; charset=utf-8 Content material-Size: 14 ETag: W/"e-gaHDsc0MZK+LfDiTM4ruVL4pUqI" Date: Wed, 15 Aug 2018 22:38:45 GMT Connection: keep-alive Good day, Server!
Add Physique Parsing Middleware
To be able to simply take care of POST
and PUT
requests to our API, we are going to add physique parsing middleware. That is the place our body-parser
module is available in. body-parser
will extract the whole physique of an incoming request and parse it right into a JSON object that we are able to work with.
We’ll merely require the module on the high of our file. Add the next require
assertion to the highest of your app.js file.
const bodyParser = require('body-parser'); ...
Then we’ll inform our Categorical app to make use of body-parser
, and search for JSON.
// Use Node.js physique parsing middleware app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ prolonged: true, }));
Additionally, let’s change our message to ship a JSON object as a response as a substitute of plain textual content.
response.ship({message: 'Node.js and Categorical REST API'});
Following is our full app.json file because it stands now.
// Require packages and set the port const specific = require('specific'); const port = 3002; const bodyParser = require('body-parser'); const app = specific(); // Use Node.js physique parsing middleware app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ prolonged: true, })); app.get('/', (request, response) => { response.ship({ message: 'Node.js and Categorical REST API'} ); }); // Begin the server const server = app.hear(port, (error) => { if (error) return console.log(`Error: ${error}`); console.log(`Server listening on port ${server.deal with().port}`); });
In the event you ship a curl -i
to the server, you will see that the header now returns Content material-Kind: utility/json; charset=utf-8
.
Set Up Routes
Thus far, we solely have a GET
path to the basis (/
), however our API ought to have the ability to deal with all 4 main HTTP request strategies on a number of URLs. We’ll arrange a router and make some pretend information to show.
Let’s create a brand new listing known as routes, and a file inside known as routes.js. We’ll hyperlink to it on the high of app.js.
const routes = require('./routes/routes');
Observe that the .js
extension is just not crucial within the require. Now we’ll transfer our app’s GET
listener to routes.js. Enter the next code in routes.js.
const router = app => { app.get('/', (request, response) => { response.ship({ message: 'Node.js and Categorical REST API' }); }); }
Lastly, export the router
so we are able to use it in our app.js file.
// Export the router module.exports = router;
In app.js, change the app.get()
code you had earlier than with a name to routes()
:
routes(app);
You must now have the ability to go to http://localhost:3002
 and see the identical factor as earlier than. (Remember to restart the server!)
As soon as that’s all arrange and dealing correctly, we’ll serve some JSON information with one other route. We’ll simply use pretend information for now, since our database is just not but arrange.
Let’s create a customers
variable in routes.js, with some pretend consumer information in JSON format.
const customers = [{ id: 1, name: "Richard Hendricks", email: "richard@piedpiper.com", }, { id: 2, name: "Bertram Gilfoyle", email: "gilfoyle@piedpiper.com", }, ];
We’ll add one other GET
path to our router, /customers
, and ship the consumer information by.
app.get('/customers', (request, response) => { response.ship(customers); });
After restarting the server, now you can navigate to http://localhost:3002/customers
and see all our information displayed.
Observe: In the event you should not have a JSON viewer extension in your browser, I extremely advocate you obtain one, comparable to JSONView for Chrome. This can make the information a lot simpler to learn!
Go to our GitHub Repo to see the finished code for this publish and examine it to your individual.
Conclusion
On this tutorial, we realized how you can arrange a built-in HTTP server and an Categorical server in node, route requests and URLs, and eat JSON information with get requests.Â
Within the ultimate installment of the RESTful API sequence, we are going to hook up our Categorical server to MySQL to create, view, replace, and delete customers in a database, finalizing our API’s performance.