0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

IntelliJで簡単なREST APIを作ります

Last updated at Posted at 2020-06-07

前回IntelliJでHelloWorldしました。

今回は簡単なREST APIを作ります。

ここを参考しました。

プロジェクトを作成

Spring initializrでプロジェクトのひな型を作成します。
image.png

Artifact: restservice
Name: restservice
Package name: restservice
Dependenciesで[Spring Web]のみ選択します。
[Generate]を押下します。

restservice.zipを解凍し、解凍されたフォルダにあるpom.xmlを右クリックします。
IntelliJで開きます。

 プロジェクトをインポート

restserviceプロジェクトはインポートされました。
image.png

モデルファイルを作成

Greeting.java
package com.example.restservice;

public class Greeting {

	private final long id;
	private final String content;

	public Greeting(long id, String content) {
		this.id = id;
		this.content = content;
	}

	public long getId() {
		return id;
	}

	public String getContent() {
		return content;
	}
}

コントローラファイルを作成

GreetingController.java
package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

	private static final String template = "Hello, %s!";
	private final AtomicLong counter = new AtomicLong();

	@GetMapping("/greeting")
	public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
		return new Greeting(counter.incrementAndGet(), String.format(template, name));
	}
}

Requestに/greetingのみであれば、defaultValue = "World"になります。

プロジェクトのビルドと実行

mainメソッドのあるDemoApplication.javaを右クリックし、Run DemoApplication mainをクリックします。

アクセスしてみる

下記のリンクをアクセスすると、
http://localhost:8080/greeting

ちゃんとレスポンスが返ってきました。


{"id":1,"content":"Hello, World!"}

下記のリンクをアクセスすると、Hello, User!が戻ってきます。
http://localhost:8080/greeting?name=User


{"id":2,"content":"Hello, User!"}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?