♊️ GemiNews 🗞️
🏡
📰 Articles
🏷️ Tags
🧠 Queries
📈 Graphs
☁️ Stats
💁🏻 Assistant
Demo 1: Embeddings + Recommendation
Demo 2: Bella RAGa
Demo 3: NewRetriever
Demo 4: Assistant function calling
Editing article
Title
Summary
Content
<p>As I’ve become more familiar with JavaScript, and more aware of the possibilities it offers, I’ve been curious about the recent trend of full-stack Javascript applications — “recent” being a relative term here, as backend JS frameworks started appearing shortly after the release of Node.js in 2009. Node, for those unfamiliar with it, is a JavaScript runtime built on Google’s V8 engine (this is what runs JavaScript in Chrome), that allows you to run JS code on a server, uncoupled from the browser. If you’d like to follow along with my code examples here, you’ll need to install Node, which you can find <a href="https://nodejs.org/en/">here</a>.</p><p>For my first foray into JavaScript on the backend, I decided to take a look at Express, one of the most popular JS web frameworks. Released in 2010, Express is a minimalist, unopinionated framework that extends the basic HTTP server functionality available in Node. As a minimalist framework, the feature set it provides out-of-the-box is limited compared to many other frameworks, but as a result of its popularity, there’s an extensive <a href="http://expressjs.com/en/resources/middleware.html">collection of middleware</a> available to add functionality as the requirements of your project necessitate.</p><p>This blog post will take a brief look at how to set up an Express server as a simple API endpoint using a MongoDB database for storage. I chose MongoDB as an opportunity to get more familiar with NoSQL databases, a concept I’ve heard about repeatedly, but that I’ve only had a vague understanding of — if you’re in the same position, and you’re familiar with SQL databases, you might be curious why we don’t have to define schema or migrations before adding data to our database. Very broadly, MongoDB is a document database that stores records as collections of documents, which are JSON-like objects composed of key:value pairs, with dynamic schema. (For a more in-depth intro to MongoDB, see <a href="https://www.codeproject.com/Articles/1037052/Introduction-to-MongoDB">here</a>)</p><h3>Getting Started</h3><p>Assuming you’ve already installed Node from the link above, the first steps are creating a project folder and getting it ready. My example here will be an API for data about beers, because beer is great, so I’ll take the obvious route and call this app “beerdb”:</p><pre>$ mkdir beerdb<br>$ cd beerdb<br>$ npm init</pre><p>The “npm init” command will ask you for a lot of info here, but you can just accept the default values, with the exception of the entry point, which i’ve changed to “server.js”</p><p>Next, we need to add a few packages to our project — Express, for obvious reasons, the MongoDB client to interface with our database, and body-parser, for parsing HTTP requests as JSON. Installing Nodemon in your dev environment is also highly recommended — it will keep an eye on your project folder and restart your server whenever your files change during development.</p><pre>$ npm install --save express<br>$ npm install --save mongodb@2.2.19<br>$ npm install --save body-parser<br>$ npm install --save-dev nodemon</pre><p>Your package.json file should look like the following, with one exception — you’ll need to add the highlighted text under “scripts” to allow Nodemon to do its thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*yl4xh_3KhSDAMHal2PiWvw.png" /></figure><p>With our packages installed, we can now get started on setting up our server — create a file called “server.js” in the root folder of your project, and add the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*jVxmZLet7otXmnCyoJ7Dew.png" /></figure><p>At this point, you can run “npm run dev” (or “npm start” if you’re not using Nodemon) in your terminal and, assuming you’ve done everything correctly your server should be up and running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*B0pC7BSGrTLh0H9PAxTiqA.png" /></figure><p>We have a server! But without any routes, it can’t do much of anything, so let’s make some routes — first, to keep our project logically organized, create an “app” folder in the root folder of your project then, within “app”, a “routes” folder containing two files — “index.js”, where we’ll export our routes for use by the server and “beer_routes.js”, where we’ll define our routes. Express requires our routes to be wrapped in a function, which needs to have our server instance and database (we don’t have a database yet, but I’ll get to that shortly) passed to it as arguments, which looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*trD44JlVv1o_JYhphpydKA.png" /></figure><p>To break down the code here a little:</p><ul><li>Line 5 uses Express’ methods to define the type of request, in this case a POST, and the route — “/beers”</li><li>Lines 6–10 grab the details about our new beer from the body of the POST request and save them to a variable</li><li>Lines 13–17 tell our database which collection we want (beers, we always want beers), and what to to that collection, insert a new document then, depending on the database’s response, returns the appropriate response to the client.</li></ul><p>In index.js, we just need to package our routes (we only have one set of routes at the moment, but as our application grows we would collect additional routes we create here) for export.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*yRnnAmmlx5Fj49CS4VygyA.png" /></figure><p>Now we have a route that should allow us to add new beers to our database, but we don’t have a database! We also don’t have a way to send data to this route to find out if it works, so it’s time for a brief digression…</p><h3>Setting up MongoDB</h3><p>If you’d like, you can host your database locally, and there are plenty of tutorials like <a href="https://www.w3schools.com/nodejs/nodejs_mongodb.asp">this one at W3Schools</a>, but for expediency I’m using <a href="https://mlab.com/">mLab</a>. Their free tier gives you up to 500MB of storage, and your choice of hosting on AWS or Azure. Once you’ve created an account, create a new database and add a database user then, from your newly created database’s page, you’ll need to grab the link that looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*icAS1Co7VEMKfzRUO3N-Rg.png" /></figure><p>Create a new folder called “config” in your project’s root folder, then a “db.js” file within “config”, where you’ll store and export your database’s URL, substituting your database user’s credentials here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*LKtXpsKrCNzf5UbJetfv1w.png" /><figcaption>Don’t put this file on GitHub!!!</figcaption></figure><p>Back in “server.js”, we need to import our db.js file and configure MongoClient to connect to the new database (this replaces our earlier call to app.listen)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*FBQo5Bd8pKYANWMtpFNCfA.png" /></figure><p>Now we should be ready to add some beers to our database, and unless you’ve already built a front-end, the best way to make sure everything is set up properly is with <a href="https://www.getpostman.com/">Postman</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*Lb5qmugkFIsQOZbeEmduxw.png" /></figure><p>Configure your POST request as shown above, send it off, and if all is well you should get a response containing your newly created document:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*5YA8DhDmxh2DlnBD5_VkUA.png" /><figcaption>Mmmm, Double Shot</figcaption></figure><p>Now that we have something in our database, it’s time to build out the rest of our routes, because what good is a database you can only add things to?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*g_jWopVnycu7mws-206-1A.png" /></figure><p>This is our GET route — if you understand what’s going on in the POST route, this isn’t much different. We’re using the findOne method to look up a document by ID, but keep in mind MongoDB expects to receive the ID as an instance of ObjectID, not a string, so we need one more line at the top of of beer_routes.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*5OHX2gxUj8HBu5yo3lBEdw.png" /></figure><p>The DELETE and PUT/PATCH routes are very similar to the GET and POST routes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*xRQTRN4W28Zj7XilZ-C8_Q.png" /></figure><p>And finally, a second GET route, this one to return the index of all the beers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*0ngUURvOpoQwTtbWYK4AdA.png" /></figure><p>With that, you’ve created a RESTful API endpoint with Express!</p><p>I’ll post this example code on GitHub shortly, so if you’re reading this I haven’t done that yet…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a78119973aa" width="1" height="1" alt="">
Author
Link
Published date
Image url
Feed url
Guid
Hidden blurb
--- !ruby/object:Feedjira::Parser::RSSEntry published: 2018-02-27 19:55:40.000000000 Z carlessian_info: news_filer_version: 2 newspaper: Kevin Randles on Medium macro_region: Technology entry_id: !ruby/object:Feedjira::Parser::GloballyUniqueIdentifier is_perma_link: 'false' guid: https://medium.com/p/9a78119973aa title: Building a RESTful API with Node, Express, and MongoDB categories: - javascript content: <p>As I’ve become more familiar with JavaScript, and more aware of the possibilities it offers, I’ve been curious about the recent trend of full-stack Javascript applications — “recent” being a relative term here, as backend JS frameworks started appearing shortly after the release of Node.js in 2009. Node, for those unfamiliar with it, is a JavaScript runtime built on Google’s V8 engine (this is what runs JavaScript in Chrome), that allows you to run JS code on a server, uncoupled from the browser. If you’d like to follow along with my code examples here, you’ll need to install Node, which you can find <a href="https://nodejs.org/en/">here</a>.</p><p>For my first foray into JavaScript on the backend, I decided to take a look at Express, one of the most popular JS web frameworks. Released in 2010, Express is a minimalist, unopinionated framework that extends the basic HTTP server functionality available in Node. As a minimalist framework, the feature set it provides out-of-the-box is limited compared to many other frameworks, but as a result of its popularity, there’s an extensive <a href="http://expressjs.com/en/resources/middleware.html">collection of middleware</a> available to add functionality as the requirements of your project necessitate.</p><p>This blog post will take a brief look at how to set up an Express server as a simple API endpoint using a MongoDB database for storage. I chose MongoDB as an opportunity to get more familiar with NoSQL databases, a concept I’ve heard about repeatedly, but that I’ve only had a vague understanding of — if you’re in the same position, and you’re familiar with SQL databases, you might be curious why we don’t have to define schema or migrations before adding data to our database. Very broadly, MongoDB is a document database that stores records as collections of documents, which are JSON-like objects composed of key:value pairs, with dynamic schema. (For a more in-depth intro to MongoDB, see <a href="https://www.codeproject.com/Articles/1037052/Introduction-to-MongoDB">here</a>)</p><h3>Getting Started</h3><p>Assuming you’ve already installed Node from the link above, the first steps are creating a project folder and getting it ready. My example here will be an API for data about beers, because beer is great, so I’ll take the obvious route and call this app “beerdb”:</p><pre>$ mkdir beerdb<br>$ cd beerdb<br>$ npm init</pre><p>The “npm init” command will ask you for a lot of info here, but you can just accept the default values, with the exception of the entry point, which i’ve changed to “server.js”</p><p>Next, we need to add a few packages to our project — Express, for obvious reasons, the MongoDB client to interface with our database, and body-parser, for parsing HTTP requests as JSON. Installing Nodemon in your dev environment is also highly recommended — it will keep an eye on your project folder and restart your server whenever your files change during development.</p><pre>$ npm install --save express<br>$ npm install --save mongodb@2.2.19<br>$ npm install --save body-parser<br>$ npm install --save-dev nodemon</pre><p>Your package.json file should look like the following, with one exception — you’ll need to add the highlighted text under “scripts” to allow Nodemon to do its thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*yl4xh_3KhSDAMHal2PiWvw.png" /></figure><p>With our packages installed, we can now get started on setting up our server — create a file called “server.js” in the root folder of your project, and add the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*jVxmZLet7otXmnCyoJ7Dew.png" /></figure><p>At this point, you can run “npm run dev” (or “npm start” if you’re not using Nodemon) in your terminal and, assuming you’ve done everything correctly your server should be up and running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*B0pC7BSGrTLh0H9PAxTiqA.png" /></figure><p>We have a server! But without any routes, it can’t do much of anything, so let’s make some routes — first, to keep our project logically organized, create an “app” folder in the root folder of your project then, within “app”, a “routes” folder containing two files — “index.js”, where we’ll export our routes for use by the server and “beer_routes.js”, where we’ll define our routes. Express requires our routes to be wrapped in a function, which needs to have our server instance and database (we don’t have a database yet, but I’ll get to that shortly) passed to it as arguments, which looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*trD44JlVv1o_JYhphpydKA.png" /></figure><p>To break down the code here a little:</p><ul><li>Line 5 uses Express’ methods to define the type of request, in this case a POST, and the route — “/beers”</li><li>Lines 6–10 grab the details about our new beer from the body of the POST request and save them to a variable</li><li>Lines 13–17 tell our database which collection we want (beers, we always want beers), and what to to that collection, insert a new document then, depending on the database’s response, returns the appropriate response to the client.</li></ul><p>In index.js, we just need to package our routes (we only have one set of routes at the moment, but as our application grows we would collect additional routes we create here) for export.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*yRnnAmmlx5Fj49CS4VygyA.png" /></figure><p>Now we have a route that should allow us to add new beers to our database, but we don’t have a database! We also don’t have a way to send data to this route to find out if it works, so it’s time for a brief digression…</p><h3>Setting up MongoDB</h3><p>If you’d like, you can host your database locally, and there are plenty of tutorials like <a href="https://www.w3schools.com/nodejs/nodejs_mongodb.asp">this one at W3Schools</a>, but for expediency I’m using <a href="https://mlab.com/">mLab</a>. Their free tier gives you up to 500MB of storage, and your choice of hosting on AWS or Azure. Once you’ve created an account, create a new database and add a database user then, from your newly created database’s page, you’ll need to grab the link that looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*icAS1Co7VEMKfzRUO3N-Rg.png" /></figure><p>Create a new folder called “config” in your project’s root folder, then a “db.js” file within “config”, where you’ll store and export your database’s URL, substituting your database user’s credentials here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*LKtXpsKrCNzf5UbJetfv1w.png" /><figcaption>Don’t put this file on GitHub!!!</figcaption></figure><p>Back in “server.js”, we need to import our db.js file and configure MongoClient to connect to the new database (this replaces our earlier call to app.listen)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*FBQo5Bd8pKYANWMtpFNCfA.png" /></figure><p>Now we should be ready to add some beers to our database, and unless you’ve already built a front-end, the best way to make sure everything is set up properly is with <a href="https://www.getpostman.com/">Postman</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*Lb5qmugkFIsQOZbeEmduxw.png" /></figure><p>Configure your POST request as shown above, send it off, and if all is well you should get a response containing your newly created document:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*5YA8DhDmxh2DlnBD5_VkUA.png" /><figcaption>Mmmm, Double Shot</figcaption></figure><p>Now that we have something in our database, it’s time to build out the rest of our routes, because what good is a database you can only add things to?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*g_jWopVnycu7mws-206-1A.png" /></figure><p>This is our GET route — if you understand what’s going on in the POST route, this isn’t much different. We’re using the findOne method to look up a document by ID, but keep in mind MongoDB expects to receive the ID as an instance of ObjectID, not a string, so we need one more line at the top of of beer_routes.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*5OHX2gxUj8HBu5yo3lBEdw.png" /></figure><p>The DELETE and PUT/PATCH routes are very similar to the GET and POST routes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*xRQTRN4W28Zj7XilZ-C8_Q.png" /></figure><p>And finally, a second GET route, this one to return the index of all the beers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*0ngUURvOpoQwTtbWYK4AdA.png" /></figure><p>With that, you’ve created a RESTful API endpoint with Express!</p><p>I’ll post this example code on GitHub shortly, so if you’re reading this I haven’t done that yet…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a78119973aa" width="1" height="1" alt=""> rss_fields: - title - url - author - categories - published - entry_id - content url: https://medium.com/@krandles/building-a-restful-api-with-node-express-and-mongodb-9a78119973aa?source=rss-d451d084d34a------2 author: Kevin Randles
Language
Active
Ricc internal notes
Imported via /Users/ricc/git/gemini-news-crawler/webapp/db/seeds.d/import-feedjira.rb on 2024-04-03 16:31:17 +0200. Content is EMPTY here. Entried: title,url,author,categories,published,entry_id,content. TODO add Newspaper: filename = /Users/ricc/git/gemini-news-crawler/webapp/db/seeds.d/../../../crawler/out/feedjira/Technology/Kevin Randles on Medium/2018-02-27-Building_a_RESTful_API_with_Node,_Express,_and_MongoDB-v2.yaml
Ricc source
Show this article
Back to articles