seon99il

Spring

What is REST-API and How to use with RestTemplate in SpringBoot

1 min read

You know, every web service has an end-point, like https://www.google.com/ or https://medium.com/, and if we send a request there (the end-point), we can get a result (HTML, CSS, JS or a value).

In this article, I’d like to introduce how to request other services in Spring Boot.

Before that, I will briefly explain REST-API.

REST Configuration

In short, a REST API consists of:

  • RESOURCE (URL)
  • Verb: (HTTP METHOD)
  • Message: (request value)

Spring @GetMapping @PutMapping @PostMapping @DeleteMapping @PatchMapping Difference — The differences between each method are described in this article.

I’ll explain it with a simple example.

ex.) Create a user named “SeongGil”: create is the method, user is the resource that is created, and SeongGil is the message.

POST) https://www.service.com/users

ex 2.) Get information of Candy A from an item: Get is the method, item is the resource, and candy is the message.

GET) https://www.service.com/item/?itemName=candy_A
{
    "itemName" : "candy_A",
    "itemPrice" : "15$"
}

Rest Characteristics

  1. Leverage a unique URI for every resource on the Web
  2. Serves a wide range of clients (Web, App)

How to use it?

Finally, let’s find out how to use it in Spring.

I’ll give you an example from code I made before.

This is a function to authenticate a business number. It uses a Korean open API.

The steps are organized like this:

  1. Define the url to request
  2. Create the Header
  3. Create the body
  4. Combine the body and header
  5. Send the Request

The header and body are Map types: header.add("key", "value"), body.add("key", "value")

This feature requires a service key and a businessNumber.

  • serviceKey: do you have permission to use this API?
  • businessNumber: which business number is this about?

I use it often, so I’ll register it as a Bean.

SellerServiceApplication.java

Service

Change the return type according to the situation.

result

tax_type: Unregistered business number

Previous posts

View all posts →

Comments