Some cURL POST request examples for self reference.
1. Normal POST
1.1 To POST without data.
$ curl -X POST http://localhost:8080/api/login/
1.2 To POST with data.
$ curl -d "username=favtuts&password=abc" http://localhost:8080/api/login/
1.3 Spring REST to accept normal POST data.
@PostMapping("/api/login")
public ResponseEntity<?> login(@RequestParam("username") String username,
@RequestParam("password") String password) {
//...
}
@PostMapping("/api/login")
public ResponseEntity<?> login(@ModelAttribute Login login) {
//...
}
2. POST + Multipart
To POST with a file, add this -F file=@"path/to/data.txt"
2.1 Upload a file
$ curl -F file=@"path/to/data.txt" http://localhost:8080/api/upload/
2.2 Upload multiple files, with extra fields :
$ curl -F extraField="abc" -F files=@"path/to/data.txt" -F files=@"path/to/data2.txt" http://localhost:8080/api/upload/multi/
2.3 Spring REST to accept POST Multipart data.
@PostMapping("/api/upload")
public ResponseEntity<?> uploadFile(
@RequestParam("file") MultipartFile uploadfile) {
//...
}
@PostMapping("/api/upload/multi")
public ResponseEntity<?> uploadFiles(
@RequestParam("extraField") String extraField,
@RequestParam("files") MultipartFile[] uploadfiles) {
//...
}
@PostMapping("/api/upload/multi2")
public ResponseEntity<?> uploadFiles2(
@ModelAttribute UploadModel model) {
//...
}
3. POST + JSON
To POST with JSON data, add this -H "Content-Type: application/json"
3.1 On Windows, escape the double quotes
c:\> curl -H "Content-Type: application/json" -X POST -d {\"username\":\"favtuts\",\"password\":\"abc\"} http://localhost:8080/api/login/
3.2 For *nix or Mac OSX, add a single quote
$ curl -H "Content-Type: application/json" -X POST -d '{"username":"favtuts","password":"abc"}' http://localhost:8080/api/login/
3.3 Spring REST to accept POST JSON data.
@PostMapping("/api/login")
public ResponseEntity<?> login(@RequestBody Login login) {
//..
}
cURL – PUT request
Example to use cURL -X PUT
to send a PUT (update) request to update the user’s name and email.
Terminal
$ curl -X PUT -d 'name=favtuts&email=abc@gmail.com' http://localhost:8080/user/100
If the REST API only accepts json formatted data, try this
$ curl -X PUT -H "Content-Type: application/json" -d '{"name":"favtuts","email":"abc@gmail.com"}' http://localhost:8080/user/100
Pretty Print JSON
In cURL requests, the default JSON output is in compact format.
Terminal
curl https://api.cloudflare.com/client/v4/
{"success":false,"errors":[{"code":7000,"message":"No route for that URI"}],"messages":[],"result":null}
In cURL, we can use or pipe the json_pp
to pretty print the JSON output.
Terminal
curl https://api.cloudflare.com/client/v4/ | json_pp
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 104 0 104 0 0 400 0 --:--:-- --:--:-- --:--:-- 398
{
"errors" : [
{
"code" : 7000,
"message" : "No route for that URI"
}
],
"success" : false,
"result" : null,
"messages" : []
}