Creating Mock Restful Services
The course is part of this learning path
This module looks at how to work with External Data in React. You’ll be looking at Class Components, Effect Hooks, and how to handle data.
The objectives of this module are to provide you with an understanding of:
- The component lifecycle
- Hooks in React
- How to create restful services
- How to use an Effect Dependency Array
- How to hand errors in data requests
- How to send data
This learning path is aimed at all who wish to learn how to use the ReactJS framework.
We welcome all feedback and suggestions - please contact us at email@example.com to let us know what you think.
When we're developing a web application, it's not guaranteed that the data services we need will be available during development. This is especially troublesome if our application is data driven and makes many requests to a data service. Wouldn't it be handy if we could mock a restful service? Well, we can. There's an npm package called JSON Server that's particularly useful if the data end point returns JSON. It claims to provide a full fake REST API with zero-coding in less than 30 seconds and it pretty much does. To use it, you need a JSON file that will act as your database and an npm installation of JSON server. You can see the command for a global installation here on the screen. Once installed, point JSON server at your file. With the --watch switch, and hey presto! Just a note, if you're using with React, JSON server runs on port 3000 by default. Which is the same port as our React server. You can change the port in JSON server by adding the -p switch and an alternative number. Say, 4000. Here we have a JSON file that contains some JSON data about courses. You can see that it is a properly formed JSON file. It had an initial key of courses and this is an array of course subjects. Firing up JSON server to watch this file and navigating to localhost:4000/courses yields all of the courses in the file. If I use the restful path courses/1, you can see that we get the course with the id of 1 returned. The console shows details of the request we have made. We may get requests, but we could also use any valid http request type to JSON server. Such as, post, put, update, and delete. This tool is really useful for us as it let's us build the correct functionality into our application without needing the actual end service. We can make requests and ensure that they work. We simply change the request url to the one for the actual service before deployment.