[JAVA] I made a function to register images with API in Spring Framework. Part 1 (API edition)

Wouldn't it be cool if the API could be delivered by a web service?

The main motive is this w Prerequisites Communication of "api.localhost" is possible. See this ヾ (.> ﹏ <.) ノ

The preparation is a subdomain for API.

specification Required library.

Library name Description
SpringFramework 5.0 I want everyone to love
Jersey JAX-RS:It is one of the implementations of Java's HTTP communication specification. Add communication function to Java
Jackson Wrapper for xml and json, convert between strings and classes

1. Make a service side

Method to controller

To make

APIPictureController.java




@RequestMapping(value="/api/picture", produces="application/json;charset=UTF-8")
@Consumes(MediaType.APPLICATION_JSON)
@RestController
public class APIPictureController {
	@Autowired
	PictureService pictureService;

	@POST
	@RequestMapping(value="/addPicture", method = RequestMethod.POST, headers = "X-SUBDOMEIN=api")
	public String addPicture( HttpServletRequest request, @RequestBody PictureMaster pictureMaster) {

		request.getHeaderNames();
		//Register the image
		Long ResultId = pictureService.addPicture(pictureMaster);
		
		PictureAddResponse response = new PictureAddResponse();
		
		response.setPictureId(ResultId.toString());
		response.setSuccessedIs(true);
		
		//Convert to json string using Jackson
		ObjectMapper mapper = new ObjectMapper();
		String json = null;
		try {
			json = mapper.writeValueAsString(response);
		} catch (JsonProcessingException e) {
			//TODO auto-generated catch block
			e.printStackTrace();
			return "{\"result\":\"failure\"}";
		}
		
		//Returns a response.
		return json;
	}

Register the image information sent as a response using the service class that has already been created.

How to receive a request

The first is how to receive an important processing request. Is the controller annotation and the arguments for this method.

@Consumes(MediaType.APPLICATION_JSON) This annotation declares that "this API accepts JSON-formatted requests". And @RequestMapping(value="/api/picture", produces="application/json;charset=UTF-8") With this produces attribute, this API returns a JSON response. I will set that.

APIPictureController.java


public String addPicture( HttpServletRequest request, @RequestBody PictureMaster pictureMaster) {

And this @RequestBody decides what class to set Json to. Of course, if you create a class that does not correspond on the client side that you will create after this, an error will be thrown, so Let's make communication that the server side and the client side can handle properly (* ^-^ *)

Do the processing

The process is called from the service class according to Spring design. See DI container, per @Autowired

PictureServiceImpl.java


	/**
	 *Register the image(API)
	 */
	@Override
	public Long addPicture(PictureMaster pictureMaster) {
		//TODO auto-generated method stub
		pictureMaster.setPictureData(Base64.getDecoder().decode(pictureMaster.getBase64string()));
		
		pRepository.saveAndFlush(pictureMaster);
		
		return pictureMaster.getPictureId();
	}

How to return the response

And the second important process is to return a response after performing the process.

First, we defined the beans needed for the response.

PictureAddResponse.java


/**
 *API communication response
 * @author nozawa
 *
 */
@Data
@ToString
public class PictureAddResponse {

	private String pictureId;
	private Boolean SuccessedIs;
}

Use the Jackson library to do this class Converts to Json character string and returns.

APIPictureController.java



		PictureAddResponse response = new PictureAddResponse();
		
		response.setPictureId(ResultId.toString());
		response.setSuccessedIs(true);
		
		//Convert to json string using Jackson
		ObjectMapper mapper = new ObjectMapper();
		String json = null;
		try {
			json = mapper.writeValueAsString(response);
		} catch (JsonProcessingException e) {
			//TODO auto-generated catch block
			e.printStackTrace();
			return "{\"result\":\"failure\"}";
		}
		
		//Returns a response.
		return json;

Use ** ObjectMapper **, a class for Json to convert. Just put the class like ** mapper.writeValueAsString (response); **. It's easy.:. ゜ ヽ (´∀`.) No.:. ゜

And let's return the string.

API side is completed

You have now provided the functionality as an API. Next, let's make this communication as a client and use this function. Continued

Recommended Posts

I made a function to register images with API in Spring Framework. Part 1 (API edition)
I made a function to register images with API in Spring Framework. Part 2 (Client Edition)
I created an api domain with Spring Framework. Part 2
I created an api domain with Spring Framework. Part 1
I made a simple search form with Spring Boot + GitHub Search API.
"Teacher, I want to implement a login function in Spring" ① Hello World
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (black magic edition)
I tried to make a login function in Java
I want to define a function in Rails Console
I tried to create a shopping site administrator function / screen with Java and Spring
I want to implement a product information editing function ~ part1 ~
I made a plugin to execute jextract with Gradle task
[Beginner] I made a program to sell cakes in Java
I want to make a function with kotlin and java!
I searched for a web framework with Gem in Ruby
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
Rails was difficult, so I made something like a controller of Spring Framework to take a break
I want to add a browsing function with ruby on rails
I made a GUI with Swing
02. I made an API to connect to MySQL (MyBatis) from Spring Boot
I made a reply function for the Rails Tutorial extension (Part 1)
I made a simple recommendation function.
I made a reply function for the Rails Tutorial extension (Part 5):
I wanted to make JavaFX programming easier with the Spring Framework
I tried to create an API to get data from a spreadsheet in Ruby (with service account)
I tried to make a group function (bulletin board) with Rails
I want to display images with REST Controller of Java and Spring!
I made an app to scribble with PencilKit on a PDF file
I want to select multiple items with a custom layout in Dialog
I tried to make a Web API that connects to DB with Quarkus
I tried to build a Firebase application development environment with Docker in 2020
I wanted to implement a slide show in a fashionable way with slick.
I want to display a PDF in Chinese (Korean) with thin reports
Create a SPA with authentication function with Rails API mode + devise_token_auth + Vue.js 3 (Rails edition)
I want to ForEach an array with a Lambda expression in Java
[LINE BOT] I made a ramen BOT with Java (Maven) + Heroku + Spring Boot (1)
I made a reply function for Rails Tutorial extension (Part 2): Change model
I made a risky die with Ruby
I made a rock-paper-scissors app with kotlin
I made a rock-paper-scissors app with android
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
I tried to make a machine learning application with Dash (+ Docker) part3 ~ Practice ~
[Rails / JavaScript / Ajax] I tried to create a like function in two ways.
03. I sent a request from Spring Boot to the zip code search API
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (Javassist second decoction)
[Go To Travel] I searched for a plan with a quo card in Jalan
Introducing # 15 pundit to build a bulletin board API with authentication authorization in Rails 6
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)
SpringSecurity I was addicted to trying to log in with a hashed password (solved)
I made a sample of how to write delegate in SwiftUI 2.0 using MapKit
I made a primality test program in Java
04. I made a front end with SpringBoot + Thymeleaf
I made a gender selection column with enum
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
I made a Docker container to run Maven
I made a Ruby extension library in C
How to add a classpath in Spring Boot
[Rails] I made a draft function using enum
[Xcode] I want to manage images in folders
I tried to link JavaFX and Spring Framework.