1+ package com.foo.rest.examples.spring.openapi.v3.httporacle.misleadingcreateput
2+
3+ import org.springframework.boot.SpringApplication
4+ import org.springframework.boot.autoconfigure.SpringBootApplication
5+ import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
6+ import org.springframework.http.ResponseEntity
7+ import org.springframework.web.bind.annotation.GetMapping
8+ import org.springframework.web.bind.annotation.PathVariable
9+ import org.springframework.web.bind.annotation.PostMapping
10+ import org.springframework.web.bind.annotation.PutMapping
11+ import org.springframework.web.bind.annotation.RequestBody
12+ import org.springframework.web.bind.annotation.RequestMapping
13+ import org.springframework.web.bind.annotation.RestController
14+
15+ @SpringBootApplication(exclude = [SecurityAutoConfiguration ::class ])
16+ @RequestMapping(path = [" /api/resources" ])
17+ @RestController
18+ open class MisleadingCreatePutApplication {
19+
20+ companion object {
21+ @JvmStatic
22+ fun main (args : Array <String >) {
23+ SpringApplication .run (MisleadingCreatePutApplication ::class .java, * args)
24+ }
25+
26+ private val data = mutableMapOf<Int , ResourceData >()
27+
28+ fun reset (){
29+ data.clear()
30+ data[0 ] = ResourceData (" existing" , 42 )
31+ }
32+ }
33+
34+ data class ResourceData (
35+ var name : String ,
36+ var value : Int
37+ )
38+
39+ data class UpdateRequest (
40+ val name : String ,
41+ val value : Int
42+ )
43+
44+ @GetMapping(path = [" /{id}" ])
45+ open fun get (@PathVariable(" id" ) id : Int ): ResponseEntity <ResourceData > {
46+ val resource = data[id]
47+ ? : return ResponseEntity .status(404 ).build()
48+ return ResponseEntity .status(200 ).body(resource)
49+ }
50+
51+ @PutMapping(path = [" /{id}" ])
52+ open fun put (
53+ @PathVariable(" id" ) id : Int ,
54+ @RequestBody body : UpdateRequest
55+ ): ResponseEntity <Any > {
56+
57+ val resource = data[id]
58+
59+ if (resource == null ) {
60+ val created = ResourceData (body.name, body.value)
61+ data[id] = created
62+ return ResponseEntity .status(201 ).body(created)
63+ }
64+
65+ // bug: returns 201 even when resource already exists
66+ resource.name = body.name
67+ resource.value = body.value
68+ return ResponseEntity .status(201 ).body(resource)
69+ }
70+ }
0 commit comments