・ Those who use external API for the first time ・ Spring-boot beginner
I am writing assuming that.
I think that companies often create microservices and provide them as external APIs. Among them, when incorporating an external API into my service, I would like to use it for future work by learning how to use the client library and basic usage such as mapping from Json format data to Java objects. I am.
By hitting the GitHub Search API, the repository is searched by language, and the repository name and user name, and the summary of the repository are acquired and displayed.
FW:spring-boot 2.2.5 Template engine: thymeleaf 3.0.4 HTTP client library: okhttp3 4.4.1 Mutual conversion library from Json to Java object: gson 2.8.6
Since Maven is used for project management, the dependency is described in pom.xml.
pom.xml
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
You can search repositories, users, issues and PR. It's very simple to use, and you don't need to register as a member in advance (however, there is a limit to the number of requests).
https://api.github.com/search/repositories?q=Search word
https://api.github.com/search/repositories?q=java
If you try entering the above URL in your browser, you will see that the results of the search with the search word "java" are displayed in your browser.
You can also search for and sort the program language by customizing it like ? Q = search word + language: ruby
(see the URL above for details).
After that, convert this content from Json to Java and display it in Thymeleaf.
Gson
[Java] JSON to Java, Java to JSON-How to use GSON and Jackson-
First, create a POJO to store Json parameters in Java as described above.
Specifically, I tapped the API appropriately, copied and pasted the parameters displayed in the browser, and created a POJO with jsonschema2pojo
. Very convenient. .. ..
If you use jsonschema2pojo
, you will get three classes, Example, Item and Owner. I renamed only ʻExample to
ResultApi`.
@SerializedName
By adding @SerializedName annotation (com.google.gson.annotations.SerializedName) to the target member, you can change the item name at the time of JSON output to any value you like.
@Expose
In standard Serializable, fields with transient are not serialized (not saved). In Gson, only fields with Expose annotation can be serialized.
Source: GSON1, [GSON2](http://www.ne.jp/asahi/hishidama/home/ tech / java / google / gson.html)
okhttp3
I referred to How to POST JSON in Java-Method using OkHttp3 and Method using HttpUrlConnection-.
Normally, when we access a web server, we use HTTP communication via a browser to access it, but the request content is only the search word, and it is displayed on the browser without any special awareness. I will. When doing that programmatically, it is a library that issues requests, creates client information, executes HTTP communication, stores response results, and so on.
DemoGetApiController.java
@Controller
public class DemoGetApiController {
@ModelAttribute
ResultApi init() {
return new ResultApi();
}
@GetMapping("/apitest")
String readme(Model model) throws IOException {
return "rest/apiTest";
}
@PostMapping("/apitest")
String search(
@RequestParam(name = "target", required = false) String target,
@RequestParam(name = "language", required = false) String language,
Model model) throws IOException {
//URL creation. The search word and radio button are acquired during post communication and stored in the URL.
String url = "https://api.github.com/search/repositories?q=" + target + "+" + "language:" + language;
//We have prepared the information required for HTTP communication. Finally, the result is stored in the Response Body.
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Call call = client.newCall(request);
Response response = call.execute();
ResponseBody body = response.body();
//The json format information is stored in the POJO created by jsonschema2pojo.
String json = body.string();
Gson gson = new Gson();
ResultApi resultApi = gson.fromJson(json, ResultApi.class);
model.addAttribute("resultApi", resultApi);
return "rest/apiTestResult";
}
}
@RequestParam (name =" target ", required = false) String target
stores the search word.
@RequestParam (name =" language ", required = false) String language
stores the programming language for radio buttons.
Please refer to the above URL for detailed usage of Gson and Http3. ResultApi / Item / Owner of POJO is omitted.
apiTest
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<link href="/css/style.css" th:href="@{/css/style.css}" rel="stylesheet" type="text/css"></link>
<title>test</title>
</head>
<body>
<form th:action="@{'/apitest'}" method="post">
<input type="text" name="target">
<button>Search</button>
<p>
<label><input type="radio" name="language" value="java" checked>java</label>
<label><input type="radio" name="language" value="ruby">ruby</label>
<label><input type="radio" name="language" value="c#">c#</label>
<label><input type="radio" name="language" value="python">python</label>
<label><input type="radio" name="language" value="javascript">javascript</label>
<label><input type="radio" name="language" value="c"> c</label>
</p>
</form>
</body>
</html>
apiTestResult
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<link href="/css/style.css" th:href="@{/css/style.css}" rel="stylesheet"
type="text/css"></link>
<title>test</title>
</head>
<body>
<a th:href="@{'/apitest'}">Return</a>
<div class="gitContents">
<div class="card card-skin" th:each="item, stat : ${resultApi.items}">
<div class="card__imgframe">
<img th:src="${item.owner.avatarUrl}">
</div>
<div class="card__textbox">
<div class="card__titletext">
<a th:href="${item.htmlUrl}"><span th:text="${item.name}"></span></a>
</div>
<div class="card__overviewtext">
<ul>
<li>USER : <span th:text="${item.owner.login}"></span></li>
<li>DESCRIPTION : <span th:text="${item.description}"></span></li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
This time, the USER name and the repository summary are extracted and displayed. In addition, you can also get the number of stars, the number of forks, etc. CSS omitted.
I think you learned how to use the basic external API. Next, on the contrary, I would like to challenge to create an API and output it in Json format! !!
Recommended Posts