Section 30 – Lessons 381, 382, 385, 386 & 387 – Complete 2020 Web Development Bootcamp

Lesson 381 – What is REST?

REST stands for Representational State Transfer.

Building an API is like building a menu of things that the server can respond to when a client makes a request.

REST is an architectural style for designing APIs. Other architectural styles for designing APIs are SOAP, GraphQL and Falcor.

There are rules that must be followed in order make an API RESTful –

  • Use HTTP Request Verbs
  • Use Specific Pattern of Routes/Endpoint URLs

The HTTP Request Verbs are:

  • GET – is the same as READ in CRUD functions;
  • POST – corresponds to CREATE in CRUD functions;
  • PUT – corresponds to UPDATE in CRUD functions – this updates database by sending an entire entry to replace an existing entry;
  • PATCH – corresponds to UPDATE in CRUD functions – this updates database by sending only the piece of data that needs to be updated;
  • DELETE – corresponds to DELETE in CRUD functions.

Lesson 382 – Creating a Database with Robo 3T

The first step is to go to https://robomongo.org/ and download Robo 3T.

Robo 3T is a graphical user interface which allows you to create mongoDB databases and insert collections and data into those databases instead of creating the databases and inserting information using the mongo shell.

Lesson 385 – GET All Articles

The first step in creating a RESTful API is to set up the route which will allow a user to get all of the articles in the database.

The get route code is –

app.get("/articles", function (req, res) {
  Article.find(function(err, foundArticles){
  	if (!err) {
  		res.send(foundArticles);
  	} else {
  		res.send(err);
  	}
  	
  });
});

Lesson 386 – POST A New Article

The next step in creating the RESTful API is to create a post route to allow the user to post an article to the database.

The post route code is –

app.post("/articles", function(req, res){
	
	const newArticle = new Article({
		title: req.body.title,
		content: req.body.content
	});
	newArticle.save(function(err){
		if(!err) {
			res.send("Successfully added a new article!");
		} else {
			res.send(err);
		}
	});
});

Lesson 387 – DELETE All Articles

Next you create a delete route to all the user to delete all the articles from the database.

The delete route code is –

app.delete("/articles", function(req, res) {
	Article.deleteMany(function(err){
		if (!err) {
			res.send("Successfully deleted all articles.");
		} else {
			res.send(err);
		}
	});
});