ページの作成
親となるページを選択してください。
親ページに紐づくページを子ページといいます。
例: 親=スポーツ, 子1=サッカー, 子2=野球
子ページを親ページとして更に子ページを作成することも可能です。
例: 親=サッカー, 子=サッカーのルール
親ページはいつでも変更することが可能なのでとりあえず作ってみましょう!
| この記事の要点 |
|---|
|
方法 1: @ResponseStatus
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
@ResponseStatus(HttpStatus.CREATED) // 201
public UserDto create(@RequestBody UserCreateRequest req) {
return userService.create(req);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT) // 204
public void delete(@PathVariable Long id) {
userService.delete(id);
}
}
方法 2: ResponseEntity(柔軟)
@GetMapping("/{id}")
public ResponseEntity get(@PathVariable Long id) {
return userService.findByIdOptional(id)
.map(user -> ResponseEntity.ok(UserDto.from(user))) // 200
.orElseGet(() -> ResponseEntity.notFound().build()); // 404
}
@PostMapping
public ResponseEntity create(@RequestBody UserCreateRequest req) {
UserDto created = UserDto.from(userService.create(req));
URI location = URI.create("/api/users/" + created.getId());
return ResponseEntity
.created(location) // 201 + Location ヘッダ
.body(created);
}
@PutMapping("/{id}")
public ResponseEntity update(@PathVariable Long id, @RequestBody UserUpdateRequest req) {
if (!userService.existsById(id)) {
return ResponseEntity.notFound().build();
}
UserDto updated = UserDto.from(userService.update(id, req));
return ResponseEntity.ok(updated);
}
// カスタムヘッダ付き
@GetMapping("/{id}/etag")
public ResponseEntity getWithEtag(@PathVariable Long id) {
User user = userService.findById(id);
return ResponseEntity.ok()
.eTag(user.getVersion().toString())
.header("X-Custom", "value")
.body(UserDto.from(user));
}
方法 3: ResponseEntity.status() で任意コード
// 任意のステータス
return ResponseEntity.status(HttpStatus.I_AM_A_TEAPOT).body(...); // 418
// よく使うショートカット
ResponseEntity.ok(body) // 200
ResponseEntity.ok().build() // 200 (body なし)
ResponseEntity.created(location).body(body) // 201
ResponseEntity.accepted().body(body) // 202
ResponseEntity.noContent().build() // 204
ResponseEntity.badRequest().body(error) // 400
ResponseEntity.notFound().build() // 404
ResponseEntity.unprocessableEntity().body(errors) // 422
ResponseEntity.internalServerError().body(error) // 500
// HttpStatus enum
return ResponseEntity.status(HttpStatus.SEE_OTHER)
.header("Location", "/new-location")
.build();
方法 4: HttpServletResponse 直接(古い書き方)
@PostMapping("/something")
public void doSomething(HttpServletResponse response) throws IOException {
response.setStatus(201);
response.setHeader("Location", "/new-resource/123");
response.getWriter().write("Created");
}
// 非推奨: ResponseEntity の方が型安全で読みやすい
例外でのステータスコード
① 例外クラスに @ResponseStatus
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long id) {
super("User not found: " + id);
}
}
// throw すると自動で 404
@GetMapping("/{id}")
public UserDto get(@PathVariable Long id) {
return userService.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
② @ExceptionHandler でステータス指定
@RestController
public class UserController {
@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleNotFound(EntityNotFoundException ex) {
return new ErrorResponse("NOT_FOUND", ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map handleValidation(MethodArgumentNotValidException ex) {
Map errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(e ->
errors.put(e.getField(), e.getDefaultMessage())
);
return errors;
}
}
③ ResponseStatusException (Spring 5+)
@GetMapping("/{id}")
public UserDto get(@PathVariable Long id) {
if (!userService.existsById(id)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found");
}
return UserDto.from(userService.findById(id));
}
// 別パターン
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid data");
throw new ResponseStatusException(HttpStatus.CONFLICT, "Duplicate entry");
throw new ResponseStatusException(HttpStatus.FORBIDDEN);
主要 HTTP ステータスコード
| コード | 意味 | 用途 |
|---|---|---|
| 200 OK | 成功 | GET / PUT 成功 |
| 201 Created | 作成成功 | POST で新規作成 |
| 204 No Content | 成功 (ボディなし) | DELETE / 一部 PUT |
| 301 Moved Permanently | 恒久リダイレクト | URL 変更 |
| 302 Found | 一時リダイレクト | ログイン後等 |
| 304 Not Modified | 変更なし (キャッシュ) | ETag / If-Modified-Since |
| 400 Bad Request | 不正なリクエスト | バリデーション失敗 |
| 401 Unauthorized | 未認証 | ログイン必要 |
| 403 Forbidden | 権限不足 | 認証済だが許可なし |
| 404 Not Found | リソースなし | 存在しない ID |
| 405 Method Not Allowed | HTTP メソッド不正 | GET 想定に POST 等 |
| 409 Conflict | 競合 | 重複・楽観ロック失敗 |
| 422 Unprocessable Entity | 構文 OK・意味エラー | バリデーション (Laravel デフォルト) |
| 429 Too Many Requests | レート制限 | API 流量制御 |
| 500 Internal Server Error | サーバエラー | 未捕捉例外 |
| 502 Bad Gateway | 上流応答不正 | nginx の背後不調 |
| 503 Service Unavailable | サービス停止 | メンテナンス・過負荷 |
| 504 Gateway Timeout | 上流応答タイムアウト | nginx タイムアウト |
REST API のステータス設計指針
| 操作 | 成功 | 失敗 (主) |
|---|---|---|
| GET /users/123 | 200 (見つかった) | 404 (ない) |
| GET /users | 200 (空配列でも 200) | 500 (DB エラー等) |
| POST /users | 201 + Location ヘッダ | 400 (構文) / 422 (検証) |
| PUT /users/123 | 200 (更新後 body) or 204 | 404 / 409 (競合) |
| DELETE /users/123 | 204 (本体なし) | 404 |
| POST /login | 200 | 401 |
| 権限なし | - | 403 |
関連記事
ページの作成
親となるページを選択してください。
親ページに紐づくページを子ページといいます。
例: 親=スポーツ, 子1=サッカー, 子2=野球
子ページを親ページとして更に子ページを作成することも可能です。
例: 親=サッカー, 子=サッカーのルール
親ページはいつでも変更することが可能なのでとりあえず作ってみましょう!
子ページ
子ページはありません
人気ページ
- 1 Eclipseで「サーバーに追加または除去できるリソースがありません。」の原因と対処法
- 2 tomcat の起動 / 停止ログと catalina.log・catalina.out の違い
- 3 JavaScript base URL 取得方法|window.location.origin と SSR/Node.js 対応
- 4 YouTube Data API v3 エラー一覧|403/400/404 の主要原因と切り分け
- 5 Spring Frameworkのアノテーション一覧
- 6 Laravel エラー一覧|500/Blade/DB 接続/ルーティングの代表エラー
- 7 3Dグラフィックスとは|モデリング/レンダリング/主要ソフトウェア (Blender / Maya)
- 8 【Spring】@Valueアノテーションとは
- 9 CATALINA_HOME の確認方法 (Linux / Mac)
- 10 【Spring】@Autowiredアノテーションとは
最近更新/作成されたページ
- Laravel キャッシュクリア完全ガイド(cache:clear / config:clear / 2026-05-18 07:42:07
- プロジェクトの作成と削除 2026-05-18 07:42:07
- インストール直後にNetbeansが反応しない 2026-05-18 07:42:07
- 動画やチャンネルの検索 2026-05-18 07:42:07
- APIキー取得方法 2026-05-18 07:42:07
- チャンネル情報の取得 2026-05-18 07:42:07
- API 入門 — Web API(REST / GraphQL / gRPC / 2026-05-18 07:42:07
- インストール(eclipseプラグイン) 2026-05-18 07:42:07
- Laravel「Dotenv values containing spaces must be surrounded 2026-05-18 07:42:07
- エラー一覧 2026-05-18 07:42:07
- curl: (51) SSL: certificate subject name '~' does not match 2026-05-18 07:42:07
- インストール方法(Windows版) 2026-05-18 07:42:07
- JSONから配列に変換 2026-05-18 07:42:07
- 処理を一定時間待つ 2026-05-18 07:42:07
- A non well formed numeric value encountered 2026-05-18 07:42:07
コメントを削除してもよろしいでしょうか?