Running and Testing with Insomnia

Insomnia is a decent REST client with a good free version. The best practice is, of course, to include code tests and implement proper error reporting in the project, but third-party REST clients are great for testing and implementing third-party solutions when error reporting and debugging the service is not available. We’ll be using it here to play the role of an application and get some insight into what is going on with our API.

To create a user, we just need to POST the required fields to the appropriate endpoint and store the generated ID for subsequent use.

Description: Request with the appropriate data for creating a user

The API will respond with the user ID:

Description: Confirmation response with userID

We can now generate the JWT using the /auth/ endpoint:

Description: Request with login data

We should get a token as our response:

Description: Confirmation containing the corresponding JSON Web Token

Grab the accessToken, prefix it with Bearer and add it to the request headers under Authorization:

Description: Setting up the headers to transfer contain the authenticating JWT

If we don’t do this now that we have implemented the permissions middleware, every request other than registration would be returning HTTP code 401. With the valid token in place, though, we get the following response from /users/:userId:

Description: Response listing the data for the indicated user

Also, as was mentioned before, we are displaying all fields, for educational purposes and for sake of simplicity. The password (hashed or otherwise) should never be visible in the response.

Let’s try to get a list of users:

Description: Request for a list of all users

Surprise! We get a 403 response.

Description: Action refused due to lack of appropriate permission level

Our user does not have the permissions to access this endpoint. We will need to change the permissionLevel of our user from 1 to 7 manually in MongoDB and then generate a new JWT.

After that is done, we get the proper response:

Description: Response with all users and their data

Next let’s test the update functionality by sending a PATCH request with some fields to our /users/:userId endpoint:

Description: Requerst containing partial data to be updated

We expect a 204 response as confirmation of a successful operation, but we can request the user once again to verify.

Description: Response after successful change

Finally, we need to delete the user. We’ll need to create a new user as described above (don’t forget to note the user ID) and make sure that we have the appropriate JWT for an admin user.

Description: Request setup for deleting a user

Sending a DELETE request to /users/:userId we should get a 204 response as confirmation. We can, again, verify by requesting /users/ to list all existing users.

Related Posts

Comments are closed.

© 2024 Software Engineering - Theme by WPEnjoy · Powered by WordPress