Kotlin+Springboot [Beginner] I can’t create Post method

Asked

Viewed 41 times

0

I didn’t even want to go to Stack in such a simple problem, but it’s already dragging on for days and I managed to implement the GET method with a certain ease, I’m learning Kotlin and java, I’m not able to implement the POST method, I’ve already tested in POSTMAN the GET and returned ok, but wanted to include the POST method to add "NEW BOOKS, AUTHORS AND PUBLISHERS", I tried several sentences, but being a beginner I am very lost.

package com.example.blog

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


data class Relatorio(
        val titulo: String,
        val autor: String,
        val serie: String
)


@RestController
@RequestMapping("/bradesco")
class BradescoController {


    @GetMapping()
    public fun relatorio(): Relatorio {
        val result = Relatorio(
                "Bradesco Prime, O Comeco",
                "Luis Carlos",
                "Coletanea Bradesco"
        )
                return result
}
    @PostMapping
    @RequestMapping("/bradesco")
    public fun relatorio2() {
        "titulo" = "A historia de Luis Carlos"
        return "Atualizado";


    }
    }

2 answers

2


The @Requestmapping is an annotation used to define a URL that will be requested:

@RequestMapping("/foo")
public fun foo() {
    return "Foo";
}

you are creating the URL: /foo

The annotation in question when applied at class level (when placed above the controller class) is not required, but when placed it transforms all its methods into relative Urls.

@RestController
@RequestMapping("/bar")
class BarController{
    @PostMapping("/foo")
    public fun foo() {
        return "Foo";
    }

In this case you are creating a URL /foo on the relative path of /bar

Soon your POST gets the way: /bar/foo

Remember that @Postmapping is a simpler way to implement @Requestmapping in the POST method.

1

Complementing @Brenno Serrato’s reply, if you want to use a POST to add new books, eventually you’ll need to receive this book you need to add to Body from your request.

It can be done that way:

@RestController
@RequestMapping("/book")
class BookController(private val bookService: BookService) {

    @PostMapping
    fun save(@RequestBody book: Book): Book {
        return bookService.save(book);
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.