2

I'm building a RESTful API using Node/Express4 and so far I've been successful. However, I'm not sure where to implement URL data validation - should the router script block invalid URI requests or should it send the controller the invalid data for it to send back an error?

The expected URI is as in the following example:

/api/:tagName/:postYear/:postMonth/:postDay

And it should return me a JSON array of posts in Year/Month/Day.

What I want is to implement a way to prevent an invalid date request from being sent to the database query, for example

/api/:tagName/20170105

Should return an error.

My doubt is whether it is more appropriate for the router to validate the year in the example (4 digits, only numeric characters) or if it should send '20170105' to the controller and have it parse the URI and throw an error back at the client.

Is there a recommended way or does either work equally well from a structural point of view?

1 Answer 1

2

Not sure this comes down to a hard-and-fast rule, but generally validation is best done as early as possible. Why waste any additional time with invalid values?

Some Node-specific things to consider:

  • Are you generating routing code with Swagger or other such tools? If so, validating the URL in the Swagger is a great contract-enforcement mechanism.
  • Are you already using something like supertest to "run" your service as part of unit tests? This makes request-level validation much simpler than actually starting a service instance for each test. If not, then it makes a lot of sense to push as much validation and logic to the controller where it can be more easily tested.

Validation aside, if the API always requires year, month and day, you might consider using changing the endpoint to use the date as a filter either as a path param (/api/myTag/20170907) or as a query parameter (/api/myTag?date=20170907). Nesting many parameters as in your example is not really true to the resource-identification paradigm of REST, and may prove to both a better UX and more easily tested. (But this too is not something which requires adherence to a strict set of rules).

1
  • Thanks. In the app I'm working at right now I've already decided it's best to change it to a URL standard query string due to multiple database search parameters being possibly sent. Still a useful reply for future works though! Commented Sep 7, 2017 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.