AI Hints
Home›Spring Boot Tutorial›Testing with curl, @RestController and @GetMapping
Spring Boot · Lesson 13 of 120

Testing with curl

Your API toolbox.

⏱ 2 min read▶ Video at 16:37🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

An API has no buttons, and no pages. To try it, we need a tool that sends requests. Curl is the simplest one, and it's already on your computer.

  • No buttons, no pages
  • A tool sends requests
  • curl is built in

Useful curl options

Curl, then a URL, sends a GET request, and prints the body. Dash i also prints the status, and the headers. Dash capital X picks the method, like POST. Dash capital H adds a header. And dash d sends data, in the request body.

OptionDoes
curl URLGET, print the body
-ishow status + headers
-X POSTchoose the method
-H "Name: value"add a header
-d '{...}'send a body

curl in action

Our controller has a GET, and a POST, on slash books. We send three requests. Run it. Plain curl shows just the body. Dash i adds the status line, and the headers, above it. And dash X POST runs the post method instead.

BookController.javajava
@RestController
public class BookController {

    @GetMapping("/books")
    public String list() {
        return "Dune, The Hobbit, Circe";
    }

    @PostMapping("/books")
    public String add() {
        return "Added!";
    }
}
Output
$ curl localhost:8080/books
Dune, The Hobbit, Circe
$ curl -i localhost:8080/books
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8

Dune, The Hobbit, Circe
$ curl -X POST localhost:8080/books
Added!
Also uses _curl.sh
curl localhost:8080/books
curl -i localhost:8080/books
curl -X POST localhost:8080/books

Other tools

Curl is great, but there are friendlier tools too. Postman, and Insomnia, give you a window with buttons. IntelliJ has a built in HTTP client. And for GET requests, your browser works too. Just type the URL.

keyvalue
curlterminal, everywhere
Postman / Insomniaapps with buttons
IntelliJ HTTP client.http files
BrowserGET requests only

Summary

Curl sends requests from the terminal. Dash i shows the status, and dash X picks the method. Next, a closer look at at Rest Controller.

Key takeaways
  • curl URL
  • -i for status
  • -X for the method
Next up: @RestController — classes that answer