[JAVA] I made a simple search form with Spring Boot + GitHub Search API.

Target audience to read the article

・ Those who use external API for the first time ・ Spring-boot beginner

I am writing assuming that.

Purpose

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.

Deliverables

GithubAPITest.gif

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.

environment

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>

About GitHub Search API

GitHub Search API Official

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.

Source code explanation

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.

controller

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.

View

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.

Impressions

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

I made a simple search form with Spring Boot + GitHub Search API.
Create a simple search app with Spring Boot
Implement a simple Rest API with Spring Security with Spring Boot 2.0
Let's make a simple API with EC2 + RDS + Spring boot ①
Implement a simple Rest API with Spring Security & JWT with Spring Boot 2.0
I made a simple MVC sample system using Spring Boot
Implement a simple Web REST API server with Spring Boot + MySQL
Create a web api server with spring boot
[LINE BOT] I made a ramen BOT with Java (Maven) + Heroku + Spring Boot (1)
03. I sent a request from Spring Boot to the zip code search API
Create a simple demo site with Spring Security with Spring Boot 2.1
I wrote a test with Spring Boot + JUnit 5 now
I made a function to register images with API in Spring Framework. Part 1 (API edition)
Try hitting the zip code search API with Spring Boot
I made a GUI with Swing
I made a simple recommendation function.
I tried GraphQL with Spring Boot
I tried Flyway with Spring Boot
I made a function to register images with API in Spring Framework. Part 2 (Client Edition)
I tried printing a form with Spring MVC and JasperReports 1/3 (JasperReports settings)
[Rails] I made a simple calendar mini app with customized specifications.
I tried printing a form with Spring MVC and JasperReports 3/3 (Spring MVC control)
02. I made an API to connect to MySQL (MyBatis) from Spring Boot
[Ruby] I made a simple Ping client
Create a simple on-demand batch with Spring Batch
I made a risky die with Ruby
I tried Lazy Initialization with Spring Boot 2.2.0
I made a rock-paper-scissors app with kotlin
I made a rock-paper-scissors app with android
Form class validation test with Spring Boot
Spring Boot Form
Create a website with Spring Boot + Gradle (jdk1.8.x)
04. I made a front end with SpringBoot + Thymeleaf
I made a mosaic art with Pokemon images
I made a gender selection column with enum
I wanted to gradle spring boot with multi-project
I made a LINE bot with Rails + heroku
Create a Spring Boot development environment with docker
I made a portfolio with Ruby On Rails
I tried printing a form with Spring MVC and JasperReports Extra edition (Variables edition)
I tried printing a form with Spring MVC and JasperReports Extra edition (image edition)
I tried to clone a web application full of bugs with Spring Boot
A simple CRUD app made with Nuxt / Laravel (Docker)
What I was addicted to when developing a Spring Boot application with VS Code
I created an api domain with Spring Framework. Part 2
Automatically map DTOs to entities with Spring Boot API
A memo that I was addicted to when making batch processing with Spring Boot
[Spring Boot] Get user information with Rest API (beginner)
[JUnit 5 compatible] Write a test using JUnit 5 with Spring boot 2.2, 2.3
SSO with GitHub OAuth in Spring Boot 1.5.x environment
Customize REST API error response with Spring Boot (Part 2)
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
I made a Restful server and client in Spring.
[Introduction to Spring Boot] Submit a form using thymeleaf
A memorandum when creating a REST service with Spring Boot
I created an api domain with Spring Framework. Part 1
Nginx + Spring Boot parrot return LineBot made with VPS
Customize REST API error response with Spring Boot (Part 1)
Download with Spring Boot
Implemented a strong API for "I want to display ~~ on the screen" with simple CQRS
I made a development environment with rails6 + docker + postgreSQL + Materialize.