JavaでREST APIサーバを構築する方法【Spring Boot入門】

はじめに

JavaでWebアプリやAPIを開発するなら、Spring Bootの利用が一般的です。REST APIの構築も簡単で、設定ファイルの記述が最小限に抑えられます。

この記事では、Spring Bootを使ってシンプルなREST APIサーバを構築する方法を、コード付きで解説します。


必要な開発環境

  • JDK 17(または11)
  • Maven or Gradle(今回はMavenを使用)
  • Spring Boot 3.x系
  • IDE(IntelliJ IDEAやVS Codeなど)

プロジェクトの作成(Spring Initializr)

  1. https://start.spring.io/ にアクセス
  2. 以下の設定でプロジェクトを生成
    • Project: Maven
    • Language: Java
    • Spring Boot: 3.x.x
    • Dependencies:
      • Spring Web
      • Spring Boot DevTools(任意)
  3. ダウンロードして展開、IDEで開く

APIエンドポイントを作成する

コントローラークラスの作成

src/main/java/com/example/demo/controller/HelloController.java

package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class HelloController {

  @GetMapping("/hello")
  public String hello(@RequestParam(defaultValue = "World") String name) {
    return "Hello, " + name + "!";
  }

  @PostMapping("/echo")
  public String echo(@RequestBody String body) {
    return "Received: " + body;
  }
}

アプリケーションのメインクラス

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

APIの動作確認

ローカルでSpring Bootアプリを実行後、以下のようにAPIをテストできます。

GETリクエスト(curlまたはブラウザ)

http://localhost:8080/api/hello?name=Spring Boot

Hello, Spring Boot! が返されます。

POSTリクエスト(curl)

curl -X POST http://localhost:8080/api/echo -H "Content-Type: text/plain" -d "こんにちは"

Received: こんにちは が返されます。

JSONに対応したAPI(DTOを使う)

データクラスの作成

package com.example.demo.dto;

public class Message {
  private String text;

  public String getText() { return text; }
  public void setText(String text) { this.text = text; }
}

コントローラーの更新

@PostMapping("/json")
public String receiveJson(@RequestBody Message message) {
  return "JSON received: " + message.getText();
}

POST JSONの送信例(curl)

curl -X POST http://localhost:8080/api/json \
  -H "Content-Type: application/json" \
  -d '{"text":"Spring Boot最高"}'

まとめ

Spring Bootを使えば、複雑な設定不要でREST APIをすぐに構築できます。フロントエンドや他システムとの連携、バッチ処理のエンドポイントなど、幅広く活用可能です。

タイトルとURLをコピーしました