1
1

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 1 year has passed since last update.

springのRequestBodyにswaggerでexampleを付与

Posted at

たとえば、下記のようにStringに @RequestBody を付与してswagger-uiで参照すると入力例があまりユーザフレンドリーでない画面になる。

@RestController
public class SampleRestController {
  @PostMapping("/sample")
  public String sample(@RequestBody String body) {
    ...

image.png

なので、サンプルとなる適当なjsonなどをデフォルトで表示したい。

適当にbuild.gradleを作る。

plugins {
  id 'org.springframework.boot' version '2.7.1'
  id 'io.spring.dependency-management' version '1.0.11.RELEASE'
  id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

configurations {
  compileOnly {
    extendsFrom annotationProcessor
  }
}

repositories {
  mavenCentral()
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-web'
  compileOnly 'org.projectlombok:lombok'
  developmentOnly 'org.springframework.boot:spring-boot-devtools'
  annotationProcessor 'org.projectlombok:lombok'
  testImplementation 'org.springframework.boot:spring-boot-starter-test'
  
  implementation 'org.springdoc:springdoc-openapi-ui:1.6.9'
}

tasks.named('test') {
  useJUnitPlatform()
}

設定例は下記な感じ。RequestBodyの名前が被ってるので冗長な記述になるのが難点。

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;

@RestController
public class SampleRestController {

  @PostMapping("/sample")
  public String sample(
      @RequestBody @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(examples = {
          @ExampleObject(name = "sample001", value = "{ \"name\": \"Tanaka\", \"age\": 26 }"),
          @ExampleObject(name = "sample002", value = "{ \"name\": \"Satou\", \"age\": 18 }")
      })) String body) {
    return "asd";
  }
}

上記の設定で下記になる。

image.png

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?