How to call and use API in Java (Spring Boot)

Premise

Dynamic web application Well, make a Servlet Service Dao or something Now you can create web pages by communicating with the server ... Study without a framework, then study the Spring framework ... But I don't understand the API! What is API!

To you

How to call API using Spring Boot I will write a memorandum!

What is API

Application programming interface It's not difficult. It's just a method. Just call a method on an external server. It's like asking someone else's house to share the vegetables.

I used to use the ingredients in my house and use the methods in my server to provide services. After all I want to use other ones too! That's why I sometimes want to call an external method.

The exchange is JSON

It's not a gecko, it's not Friday the 13th JavaScript Object Notation {id: 1245, name:'Taro', comment:'Wow!'} Such a guy! Variable name: the one inside How to write by separating This is how to write JSON

Even if you suddenly say that, it feels like ...

In the first place ...

API is also a method

So it has an argument and a return value. The basic API is called Service!

My house → (I'll give you tomatoes!) → The other party's house My house ← (Cucumber to return!) ← The other party's house

In other words

My Service → (Request) → Other Service My Service ← (Response) ← Other Service

For this request and response, I use Bean, Model, Entity, or something like that.

In other words, this guy!

I'll give you one! Tomato Entity!

TomatoEntity.java


@Component
public class TomatoEntity {
    //id
    private String id;
    //name
    private String name;
    //comment
    private String comment;

    //Below, getters and setters
    public String getId() {
      return id;
    }
    public String setId(String id) {
      this.id = id;
    }

    public String getName() {
      return name;
    }
    public String setName(String name) {
      this.name = name;
    }

    public String getComment() {
      return comment;
    }
    public String setComment(String comment) {
      this.comment = comment;
    }

    //With Eclipse
    //Alt+Shift+From the S menu
    //Alt+Select getter setter generation in R
    //Alt+Select all with A
    //Alt+Created with R! What
    //If you keep pressing Alt all the time, you can make it immediately!
}

Cucumber Entity for response!

KyuuriEntity.java


@Component
public class KyuuriEntity {
    //date
    private Date day;
    //Array of messages
    private List<String> message;

    //Below, getters and setters
    public Date getDay() {
      return day;
    }
    public Date setDay(String day) {
      this.day = day;
    }

    public List<String> getMessage() {
      return message;
    }
    public list<String> setMessage(List<String> message) {
      this.message = message;
    }

    //Well, if it's Spring, it's an annotation
    //Because there is a getter setter
    //You don't have to make a method...
}

So

My Service → (Tomato Entity) → The other party's Service My Service ← (Kyuuri Entity) ← Other Service

That's it!

So, I will convert this to JSON and exchange it

My Service → (Tomato Entity) → (Tomato that became JSON) → Service of the other party My Service ← (Return to Kyuuri Entity) ← (JSON Kyuuri) ← Other Service

Well, if you recognize it like this

If you know that you are exchanging with JSON, you do not need to be aware of it!

More specifically!

Well, it's fluffy and it's hard to grasp the actual situation, I think it's hard to understand Please give a concrete example (various strange but easy to understand!)

CallApiService.java


@Service
public class CallApiService {
    //First make a request
    TomatoEntity tomato = new Tomatoentity();
    tomato.setId("831");
    tomato.setName("Tomato");
    tomato.setComment("delicious");

    //Make a request to send to the API
    RequestEntity<TomatoEntity> request = RequestEntity
        .post(new URI("http://kyuuri.api"))
        .accept(MediaType.APPLICATION_JSON)
        .body(tomato);

    //Response is returned from API
    ResponseEntity<KyuuriEntity> response = restTemplate
        .exchange(request, Kyuuri.class);
}

Commentary! !!

·request

Create the tomato Entity you set earlier and throw it as a request to the outside API RequestEntity is a type provided by the Spring framework This is the box that wraps the tomatoes sent to the API The tomato Entity is packed in a box and delivered. new URI is Java.net.URI It's an address. You understand Convert to JSON type with MediaType.APPLICATION_JSON in.accept () As I wrote earlier, it means exchanging with JSON! .body () is the information of the contents of the request This time I'm packing the tomato Entity I made above

In other words, this kind of thing


RequestEntity<Type of entity to send>Favorite name
    = 
    RequestEntity.post(Destination url).accept(json).body(Contents of the sent entity)

·response

CallApiService.java


@Service
public class CallApiService {
    //First make a request
    TomatoEntity tomato = new Tomatoentity();
    tomato.setId("831");
    tomato.setName("Tomato");
    tomato.setComment("delicious");

    //Make a request to send to the API
    RequestEntity<TomatoEntity> request = RequestEntity
        .post(new URI("http://kyuuri.api"))
        .accept(MediaType.APPLICATION_JSON)
        .body(tomato);

    //Response is returned from API
    ResponseEntity<KyuuriEntity> response = restTemplate
        .exchange(request, Kyuuri.class);
}

A response is returned from the external API to the cucumber Entity set earlier. So you have to know the shape of the return value from the API. ResponseEntity is a type provided by the Spring framework This is the box that wraps the cucumbers that come back from the API The cucumber Entity is packed in the box and arrives. There is a handy guy called restTemplate For more information RestTemplete Official Reference .exchange is a method of RestTemplete When the request enters the API, the return value is output as the specified type. Well, this is not the API (argument, return value)

In other words, this kind of thing


ResponseEntity<Back entity type>Favorite name= restTemplete
                    .exchange(Request variable name,Back type.class);

Originally a little more method followed Connection and response timeout settings Authentication, followed by validation The error status code is sticking to me.

The API is done like this! If you understand that, this is enough!

Then finally

CallApiService.java


@Service
public class CallApiService {
    //First make a request
    TomatoEntity tomato = new Tomatoentity();
    tomato.setId("831");
    tomato.setName("Tomato");
    tomato.setComment("delicious");

    //Make a request to send to the API
    RequestEntity<TomatoEntity> request = RequestEntity
        .post(new URI("http://kyuuri.api"))
        .accept(MediaType.APPLICATION_JSON)
        .body(tomato);

    //Response is returned from API
    ResponseEntity<KyuuriEntity> response = restTemplate
        .exchange(request, Kyuuri.class);

    //Handle the returned value
    KyuuriEntity kyuuriResponse = response.getBody();
}

With .getBody (), you can retrieve the cucumber Entity as set here. In addition, the return value from the API is included inside. You've just hit another API!

so?

Yup. Specifically, everyone should experiment and try various things. I'm writing a memorandum to the last, so it may be messy, but I'm glad if it helps!

See you soon!

Recommended Posts

How to call and use API in Java (Spring Boot)
How to use CommandLineRunner in Spring Batch of Spring Boot
How to use Lombok in Spring
How to use ModelMapper (Spring boot)
How to use classes in Java?
Multilingual Locale in Java How to use Locale
How to set and use profile in annotation-based Configuration in Spring framework
[Java] How to use FileReader class and BufferedReader class
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to use built-in h2db with spring boot
How to use Spring Boot session attributes (@SessionAttributes)
How to add a classpath in Spring Boot
How to use Java API with lambda expression
How to bind to property file in Spring Boot
[Java] How to use Calendar class and Date class
[Java] How to use Map
[Java] How to use Map
How to use java Optional
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to use string.format
How to use Java Map
How to use Java variables
[Java] How to use Optional ①
How to call functions in bulk with Java reflection
How to create a Spring Boot project in IntelliJ
Summary of Java communication API (1) How to use Socket
Summary of Java communication API (3) How to use SocketChannel
How to convert A to a and a to A using AND and OR in Java
Introduce swagger-ui to REST API implemented in Spring Boot
Summary of Java communication API (2) How to use HttpUrlConnection
How to use In-Memory Job repository in Spring Batch
Notes on how to use regular expressions in Java
How to use StringBurrer and Arrays.toString.
How to use Java HttpClient (Get)
How to change application.properties settings at boot time in Spring boot
How to use EventBus3 and ThreadMode
How to use Spring Data JDBC
Handle Java 8 date and time API with Thymeleaf with Spring Boot
How to implement authentication process by specifying user name and password in Spring Boot
How to use Java HttpClient (Post)
[Java] How to use join method
How to set Spring Boot + PostgreSQL
How to call classes and methods
How to use equality and equality (how to use equals)
[Processing × Java] How to use variables
What happened in "Java 8 to Java 11" and how to build an environment
How to use InjectorHolder in OpenAM
[Java] How to use LinkedHashMap class
Implement REST API in Spring Boot
How to use Java enums (Enum) in MyBatis Mapper XML
Create API to send and receive Json data in Spring
[JavaFX] [Java8] How to use GridPane
Reasons to use Servlet and JSP separately in Java development
How to use class methods [Java]
[Java] How to use List [ArrayList]
How to name variables in Java
How to develop and register a Sota app in Java
Differences in how to handle strings between Java and Perl
[Processing × Java] How to use arrays