--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
--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
}
Please refer to another article for details. Create a Gradle Spring Boot project
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;
}
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;
}
--Access "localhost: 8080" with a browser
--Enter "100-0001" (Zip code of the Imperial Palace) and press the address acquisition button
--The address is displayed.
___ 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;
}
}
--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