[JAVA] [API] I tried using the zip code search API

Try to make an application using API

background

--The number of applications using API is increasing --The work of engineers who make APIs is increasing. ――Demand for technology that handles APIs is likely to increase

table of contents

0. Environmental check

1. Check API

--Check the API usage from the following site. https://zip-cloud.appspot.com/doc/api

--Check the specifications. --Based on https://zip-cloud.appspot.com/api/search --Request parameters

 |Parameter name|item name|Mandatory|Remarks|
 | ---- | ---- | ---- | ---- |
 |  zipcode  |Postal code|  ○  |7 digit number. Can be with a hyphen. Exact match search.|
 |  callback  |Callback function name|  -  |Callback function name when outputting as JSONP. UTF-A URL-encoded string in 8.|
 |  limit  |Maximum number|  - |Maximum number of items returned when multiple items exist with the same zip code (number) * Default: 20|

--Response parameters

 |Field name|item name|Remarks|
 | ---- | ---- | ---- |
 |  status  |status|200 is returned when normal, and an error code is returned when an error occurs.|
 |  message  |message|When an error occurs, the content of the error is returned.|
 |  results  | zipcode(Postal code) <br> prefcode(Prefecture code)<br> address1(Name of prefectures) <br> address2(City name)<br>address3(Town area name) <br>kana1(Name of prefecturesカナ)<br>kana2	(City nameカナ) <br>kana3(Town area nameカナ) |If there are multiple, it will be an array|

-(Example) When searching by zip code "7830060" --Request URL https://zip-cloud.appspot.com/api/search?zipcode=7830060 --Response
{ "message": null, "results": [ { "address1": "Hokkaido", "address2": "Bibai", "address3": "Kyowa Kamimi Utamachi", "kana1": "Hokkaidou", "kana2": "Visit", "kana3": "Kamibi Ginkgo", "prefcode": "1", "zipcode": "0790177" }, { "address1": "Hokkaido", "address2": "Bibai", "address3": "Kami Utacho Minami", "kana1": "Hokkaidou", "kana2": "Visit", "kana3": "Kamibi Ginkgo Minami", "prefcode": "1", "zipcode": "0790177" } ], "status": 200 }

2. Create a project

Please refer to another article for details. Create a Gradle Spring Boot project

3. Backend implementation

build.gradle


//Omission
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
	compile("com.fasterxml.jackson.core:jackson-databind")
}


--Controller class --Pattern 1: Received as a Json format character string

FrontController.java


@Controller
public class FrontController {

	@Autowired
	private FrontService frontService;

    @RequestMapping({ "/", "/index" })
    public String index() {
    	return "index";
    }
	@ResponseBody
    @RequestMapping(value = "/getAddress" ,method = RequestMethod.POST, produces="application/json;charset=UTF-8")
    public String getAddress(@RequestBody(required = false) AddressForm addressForm) {
		return frontService.getAddress(addressForm.getZipcode());
    }
}

--Service class

FrontService.java


public interface FrontService {
	public String getAddress(String zipCode);
}

FrontServiceImpl.java


@Service
public class FrontServiceImpl implements FrontService {

    /**Zip Code Search API Request URL*/
    private static final String URL = "https://zip-cloud.appspot.com/api/search?zipcode={zipcode}";

	@Override
	public String getAddress(String zipCode) {
		String zipCodeJson = restTemplate.getForObject(URL, String.class, zipCode);
		return zipCodeJson;
	}
}

--form class

AddressForm.java


@Data
public class AddressForm {

	/**Postal code*/
	String zipcode;
}

4. Front end implementation

index.html


<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>address</title>
		<script type="text/javascript" th:src="@{/jquery/jquery-3.3.1.js}"></script>
		<script th:src="@{/js/index.js}"></script>
	</head>
	<body>
		<form name="getAddress">
			<input id="zipcode" type="text">
			<button type="button" id="getAddressBtn">Address acquisition</button>
			<div id="dispAddress"></div>
		</form>
	</body>
</html>

index.js


$(function() {
	$('#getAddressBtn').on('click', function() {
		var params = {
				"zipcode" : $('#zipcode').val()
		};
		$.ajax({
			url : 'getAddress',
			type: 'POST',
			contentType: "application/json",
	        data: JSON.stringify(params),
			dataType : 'json',
			async: false,
			success: function (data) {
				$("#dispAddress").empty();
			    var dispAddress = document.getElementById("dispAddress");
				var table = document.createElement("table");
				table.setAttribute("border","2");
				table.setAttribute("cellpadding","15");
				table.setAttribute("style","margin :15px");

			    $(data.results).each(function(index, result){
					table.appendChild(createRow("Postal code",result.zipcode));
					table.appendChild(createRow("Prefecture code",result.prefcode));
					table.appendChild(createRow("Name of prefectures",result.address1));
					table.appendChild(createRow("City name",result.address2));
					table.appendChild(createRow("Town area name",result.address3));
					table.appendChild(createRow("Prefecture name Kana",result.kana1));
					table.appendChild(createRow("Municipality name Kana",result.kana2));
					table.appendChild(createRow("Town area name Kana",result.kana3));
			    });
				dispAddress.appendChild(table);
			}
		});
	});
});

function createRow(header , value){
	var tr = document.createElement("tr");
	var th = document.createElement("th");
	th.append(header);
	var td = document.createElement("td");
	td.append(value);
	tr.appendChild(th);
	tr.appendChild(td);
	return tr;
}

5. Operation check

--Access "localhost: 8080" with a browser ブラウザ起動.png

--Enter "100-0001" (Zip code of the Imperial Palace) and press the address acquisition button ブラウザ起動2.png

--The address is displayed.

6. Bonus

___ How to convert Json format to DTO class and receive ___ --Controller class

FrontController.java


@Controller
public class FrontController {

	@Autowired
	private FrontService frontService;

    @RequestMapping({ "/", "/index" })
    public String index() {
    	return "index";
    }
	@ResponseBody
    @RequestMapping(value = "/getAddress" ,method = RequestMethod.POST, produces="application/json;charset=UTF-8")
    //Change the return value from String to ZipcodeDto
    public ZipcodeDto getAddress(@RequestBody(required = false) AddressForm addressForm) {
		return frontService.getAddress(addressForm.getZipcode());
    }
}

--Service class (correction)

FrontService.java


public interface FrontService {
    //Change the return value from String to ZipcodeDto
	public ZipcodeDto getAddress(String zipCode); 
}

--DTO class (additional)

ZipcodeDto.java


@Data
public class ZipcodeDto {
    /**status*/
    int status;

    /**message*/
    String message;

    /**Postal code information list*/
    List<ZipcodeResultDto> results = new ArrayList<>();
}

--DTO class (additional)

ZipcodeResultDto.java


@Data
public class ZipcodeResultDto {

	/**Postal code*/
    String zipcode;

    /**Prefecture code*/
    String prefcode;

    /**Name of prefectures*/
    String address1;

    /**City name*/
    String address2;

    /**Town area name*/
    String address3;

    /**Prefecture name Kana*/
    String kana1;

    /**Municipality name Kana*/
    String kana2;

    /**Town area name Kana*/
    String kana3;
}

--Service implementation class --Pattern to pass URL to ObjectMapper and convert to DTO class

FrontServiceImpl.java


@Service
public class FrontServiceImpl implements FrontService {
     //Added ObjectMapper
	@Autowired
	ObjectMapper objectMapper;

     //Change URL parameters to regular expressions
    private static final String URL = "https://zip-cloud.appspot.com/api/search?zipcode=%s";

	@Override
	public ZipcodeDto getAddress(String zipCode) {
		ZipcodeDto zipcodeDto = null;;
		try {
            //Specify URL and receiving class in ObjectMapper
			java.net.URL url = new java.net.URL(String.format(URL,zipCode));
			zipcodeDto = objectMapper.readValue(url, ZipcodeDto.class);
		} catch (Exception e) {
			e.getStackTrace();
		}
		return zipcodeDto;
	}
}

--Service implementation class --Pattern to convert by setting MappingJackson2HttpMessageConverter in restTemplate

FrontServiceImpl.java


@Service
public class FrontServiceImpl implements FrontService {

     //Added restTemplate
	RestTemplate restTemplate = new RestTemplate();

    private static final String URL = "https://zip-cloud.appspot.com/api/search?zipcode={zipCode}";

	@Override
	public ZipcodeDto getAddress(String zipCode) {
		ZipcodeDto zipcodeDto = null;;
		try {

           //Added MappingJackson2HttpMessageConverter to messageConverter of reatTemplate
			MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
		    List<MediaType> supportedMediaTypes = new ArrayList<>(messageConverter.getSupportedMediaTypes());
		    supportedMediaTypes.add(MediaType.TEXT_PLAIN);
		    messageConverter.setSupportedMediaTypes(supportedMediaTypes);
		    restTemplate.setMessageConverters(Collections.singletonList(messageConverter));
			zipcodeDto = restTemplate.getForObject(URL, ZipcodeDto.class, zipCode);
		} catch (Exception e) {
			e.getStackTrace();
		}
		return zipcodeDto;
	}
}

7. Summary

--Easy to use API (a little more difficult with authentication function) --Data can be used from other APIs ――It seems that you can create a new service by combining various APIs.

Recommended Posts

[API] I tried using the zip code search API
Try using the Rails API (zip code)
03. I sent a request from Spring Boot to the zip code search API
I tried using Java8 Stream API
Try hitting the zip code search API with Spring Boot
The code I used to connect Rails 3 to PostgreSQL 10
[API] I tried using the zip code search API
I tried using Elasticsearch API in Java
I tried to summarize the Stream API
I tried using Docker for the first time
I tried using Gson
I tried using TestNG
I tried using Galasa
I tried using the profiler of IntelliJ IDEA
Rails API mode I tried to implement the keyword multiple search function using arrays and iterative processing.
I tried using the Server Push function of Servlet 4.0
I tried using Google Cloud Vision API in Java
I tried using the Migration Toolkit for Application Binaries
[Java] I tried to implement Yahoo API product search
I tried using azure cloud-init
I tried the Docker tutorial!
I tried using Apache Wicket
I tried the VueJS tutorial!
I tried using Java REPL
I tried source code analysis
I tried the FizzBuzz problem
I tried using the GitHub repository as a library server
I tried to introduce UI animation to Pokedex using Poké API
I tried to build the environment little by little using docker
I tried using the CameraX library with Android Java Fragment
I tried using anakia + Jing now
I tried something called recursive search
I tried using Spring + Mybatis + DbUnit
I tried using JOOQ with Gradle
I tried to explain the method
I tried the Java framework "Quarkus"
[Rails] I tried deleting the application
I tried using JWT in Java
[Android] I tried using Coordinator Layout.
I tried using Pari gp container
I tried using WebAssembly Stadio (2018/4/17 version)
I tried using Java memo LocalDate
I tried using GoogleHttpClient of Java
[Metal] I tried to figure out the flow until rendering using Metal
I tried using the cache function of Application Container Cloud Service
Sample code to call the Yahoo! Local Search API in Java
I tried to display the calendar on the Eclipse console using Java.
[Swift] Hit the API using Decodable / Generics
I tried using Realm with Swift UI
I tried migrating Processing to VS Code
I tried using Java's diagnostic tool Arthas
I tried using UICollectionViewListCell added from Xcode12.
A story I was addicted to when testing the API using MockMVC
Try using the Stream API in Java
I tried using Scalar DL with Docker
I tried the new era in Java
[Ruby] I tried to diet the if statement code with the ternary operator
I tried to solve AOJ's Binary Search
I tried using OnlineConverter with SpringBoot + JODConverter
It's new, but I tried using Groonga
I tried to implement the Iterator pattern
I tried running the route search engine (OSRM) easily with a container