Week 14 - Middleware & REST

Week 14 - Middleware & REST

·

8 min read

To supplement our current bootcamp project, we've been learning some more in-depth concepts and principles about back-end development. It was nice to have some lectures that were a little lighter, as I'm definitely still absorbing from previous weeks!

So, what did week 14 look like?

Express Middleware

Middleware functions have access to the request object req, the response object res, and the next middleware function in the application’s request-response cycle; middlewares are executed in the middle after the incoming request and before the controller function. Middleware can produce an output which could be the final output passed or could be used by the next middleware until the request-response cycle is completed, therefore you can have more than one middleware and they will execute in the order they are declared.

Middleware stack image

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • Send a response and prevent the controller being accessed.
  • End the request-response cycle.
  • Call the next middleware in the stack.

To set up a middleware, you can invoke app.use() for every middleware layer that you want to add. Middleware can sit at app level or at route level, application level middleware will apply to all requests, route level will only apply to requests to that specific route.

The next middleware function is commonly denoted by a variable named next. If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left waiting. Controller functions are types of middleware, the different is that controller functions always send a response and do not pass to next.

On the app level:

app.use(express.static('/public'));
router.use(express.json());

On a route level:

app.use('/user/:id', function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})

Middleware is often used to manage some common tasks that are not managed by any single controller function, such as:

  • Authentication
  • Request Body Validation
  • Logging
  • Error handling

You can read the Express Middleware documentation here. I found it really easy to absorb and actually, the things you can do with middleware is quite exciting. You can see examples of the four common tasks above in the documentation. Express also comes with a few built-in middlewares (exciting right!) express.json is a fairly common example, and parses JSON (JavaScript Object Notation) requests. If you wish, you can write your own middlewares or install more from NPM.

For a comprehensive go here's a good blog post with a code along demo

RESTful API Design

REST (REpresentational State Transfer) is an architectural style, a guide to how your API should be structured. REST is just one type of API, there are others. RESTful structure are characterised with several principles:

  • The interface allows for scalability.
  • Routes can be built up, or created without affecting existing behaviour in the API.
  • Routes are independent and do not keep an internal state (stateless).
  • The concerns of client and server are kept separate.
  • Clients send requests and the server sends the response to those requests.
  • REST APIs access resources (a URI) to respond to the client requests.

REST APIs use REST methods for all CRUD (create, read, update, delete) operations. If not needed, you don't have to use all the methods and only one method type is used per URI. Some frequently used methods include GET, POST, PUT, PATCH and DELETE, here is some clear definitions and examples. Responses from the server contain particular status codes which alert the client about the success of the operation, these also relate to the method used, please see here for some common ones.

Best Practices

We also discussed some best practices for when building projects, some which we talked about are:

Best Practice
VersioningTrack when features added and improvements made. Quickly review and see where breaking changes (any change to an aspect of the API that the consumer relies on) were made. Easy to revert back to previous versions.
DocumentationInclude a list of all the routes. Describe what the expected request body and parameters are. Describe what a user can expect to receive from a request (data, structure, response codes).
ConventionsRoutes are always lower case. Nouns represent resources. Use forward slash to represent hierarchal relationships in paths.

Here's to week 15 of bootcamp!

My Key Take Aways

Seize Opportunities - We're all new at this, it's scary, but everyone was new once! If something fortuitous comes your way, why not give it a go! I felt that way about Hacktoberfest and it was so nice to just have a go. I've also recently signed up to exercism, as it was recommended by a friend, to keep practising in a different format!

Grow your network - You never know what you might learn from someone or who you might meet so I encourage you to grow your network. Here, on Twitter, on LinkedIn, within your coding buddies - it might be a great surprise what you can discover and who can help you on your way.

There's a lot of ways to do things - As we have been working on our projects it's been fantastic to see how people tackle problems; there are some clear similarities and also some big differences. There is so much variety in the world of software development. I personally think it's fantastic, because what is life without a little variety!