I am building a RESTful API, and so far, to make sure that my resources work as I need them to, I am using a REST client called Postman. This makes it easy for me to store routes and quickly make requests to them for testing. My current collection of routes in Postman looks like this:
The trouble with testing the API is this way is I have to manually change resource IDs. For example, if I want to test the PUT
method on my posts resource, I have to first create a resource, find the ID, and then paste it into the PUT
URI. This is long!
What is considered professional practice for building a RESTful API? Should I be writing unit tests for each route, dynamically creating the post before testing methods like update?
Testing any kind of API is very difficult to do manually, especially without a UI that uses it. As soon as you find manual testing is getting tricky or tedious, that’s a sure sign that you need some automated tests.
You could write integration tests from the HTTP level which first call the API to setup the data appropriately. But writing true unit tests might be preferable if you have multiple layers of code under your API. You can stub and mock the calls to the data service to avoid having to call the API several times per test.
I would develop a client program for my REST API (I used to do Python, but nowadays why not using Node.JS). This is the best way to test, because you’re actually using it, and, moreover, you can launch your program as much time as you want and automate the testing using a testing lib. This is not that long to write, and really, it gives you some interesting software quality point.
This is not unit testing, this is a pure functional testing, it’s about giving some garanty to your user that it works as expected.
Extra point: if you want to test some more global website (not just API) under the same approach, I would suggest you to give a try at CasperJS.