ResponseEntityでの各HTTPステータスレスポンス作成方法

はじめに

本記事では、Springで提供されているResponseEntityを使用したレスポンス作成方法について記述します。
主にHTTPステータス200系(成功)と、400・500系(エラー)の取り扱い方法です。
(個人的によく使うものだけです。悪しからず)

ResponseEntityとは

ResponseEntityは、その名の通り、レスポンスを表現するためのクラスです。
以下、ドキュメントから抜粋です。

HttpStatus ステータスコードを追加する HttpEntity の拡張。RestTemplate および @Controller メソッドで使用されます。

それでは以下、各HTTPステータスごとの書き方を列挙していきます。

なお、コードはKotlinで書きますが、Javaとそう大きく変わりませんので、Java使いの方も理解は難しくないかと思います。

共通の例

はじめに、ResponseEntityにHTTPステータスを設定する方法を書いてしまいます。

ResponseEntity.status(200).build

はい、上記のように、status(XXX)の部分を変えてしまえば、期待するHTTPステータスを持ったResponseEntityを作成することができます。
以降で紹介するのは上記コードを実現するためにあらかじめ用意されているメソッド群の紹介となります。

200系(成功)

200 OK

    // 200 no body
    fun sample200(): ResponseEntity<Void> {
        return ResponseEntity.ok().build()
    }

    // 200 contains response body
    fun sample200Body(): ResponseEntity<String> {
        return ResponseEntity.ok("Hello, World!")
        // ResponseEntity.ok().body("Hello, World!")と等価
    }

201 Created

    // 201
    fun sample201(): ResponseEntity<Void> {
        val uri = URI.create("created/uri")
        return ResponseEntity.created(uri).build()
    }

202 Accepted

    // 202
    fun sample202(): ResponseEntity<Void> {
        return ResponseEntity.accepted().build()
    }

204 No Content

    // 204
    fun sample204(): ResponseEntity<Void> {
        return ResponseEntity.noContent().build()
    }

400・500系(失敗)

400 Bad Request

    // 400
    fun sample400(): ResponseEntity<Void> {
        return ResponseEntity.badRequest().build()
    }

401 Unauthorized

    // 401
    fun sample401(): ResponseEntity<Void> {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()
    }

403 Forbidden

    // 403
    fun sample403(): ResponseEntity<Void> {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).build()
    }

404 Not Found

    // 404
    fun sample404(): ResponseEntity<Void> {
        return ResponseEntity.notFound().build()
    }

500 Internal Server Error

    // 500
    fun sample500(): ResponseEntity<Void> {
        return ResponseEntity.internalServerError().build()
    }

終わりに

以上、よく使うであろうHTTPステータスごとのResponseEntityオブジェクトの生成方法でした。
ResponseEntityは内部的にBuilderパターンによるオブジェクト生成を行っているため、HTTPステータス以外にもヘッダーなどを設定するに便利なメソッドが多数用意されています。
それらもいずれ紹介できればと思います。