Monday, June 6, 2022
HomeWeb DevelopmentCode Your First API With Node.js and Categorical: Set Up the Server

Code Your First API With Node.js and Categorical: Set Up the Server


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.

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.

Now that we’re in our new listing, we are able to initialize our undertaking with the init command.

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:

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.

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:

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.

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.

Lastly, we are going to inform the server which port to hear on, and show an error if there’s one.

Now, we are able to begin our server with node adopted by the filename.

You will notice this response within the terminal:

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.

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.

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.

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.

Lastly, we’ll begin the server on port 3002 with the hear() technique.

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.

Now we are able to use npm begin to begin the server, and we’ll see our server message within the terminal.

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.

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.

Then we’ll inform our Categorical app to make use of body-parser, and search for JSON.

Additionally, let’s change our message to ship a JSON object as a response as a substitute of plain textual content.

Following is our full app.json file because it stands now.

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.

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.

Lastly, export the router so we are able to use it in our app.js file.

In app.js, change the app.get() code you had earlier than with a name to routes():

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.

We’ll add one other GET path to our router, /customers, and ship the consumer information by.

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.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments