How to Set Up a Quick Mock API with Spring by Serving JSON Data

Ye Min Ko
2 min readSep 18, 2024

--

Photo by Uillian Vargas on Unsplash

Mock API

Sometimes we need a mock API that returns data from a JSON file. This is easy to implement in the JavaScript world, but for Spring, we can achieve something similar with the following workaround.

Prepare JSON file

Create a JSON file that includes the data you want as the response. Place the file under the main/resources folder. For example:

dummary.json under resources/json folder

Create Mock API

Write a Spring REST API that reads data from a JSON file and returns it as the response, as follows:

@GetMapping("/api/mock")
public ResponseEntity<?> getMockData() {
String data = "";
ClassPathResource cpr = new ClassPathResource("json/dummary.json");
try {
InputStream inputStream = cpr.getInputStream();
byte[] bdata = FileCopyUtils.copyToByteArray(inputStream);
data = new String(bdata, StandardCharsets.UTF_8);
return ResponseEntity.ok(data);
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok(data);
}

Done

That’s it! Now you can use the mock API to get JSON data. You can change any JSON structure, and the API will serve it for you.

--

--

Ye Min Ko

🌐 Web Developer | 👀 Self-Learner | 👨‍💻 An Introvert