6.4. Testing APIs with cURL#

curl is a command-line tool used to send HTTP requests to servers. It is most commonly used to test the behaviour of websites or to scrape data automatically.

6.4.1. GET Requests#

By default curl will send a GET request to the server.

Retrieving all books

curl http://localhost:5000/api/books

Retrieving a single book with id == 2

curl http://localhost:5000/api/books/2

6.4.2. POST Requests#

Use -X POST to set the HTTP method

curl -X POST http://localhost:5000/api/books \
    -H "Content-Type: application/json" \
    -d '{"title": "Dune", "author": "Frank Herbert"}'
  • -H adds a custom header (here, specifying JSON)

  • -d sends data in the body of the request

Note

The “" allows us to spread a command over multiple lines on the terminal.

6.4.3. PUT Requests#

curl -X PUT http://localhost:5000/api/books/1 \
    -H "Content-Type: application/json" \
    -d '{"title": "Dune (Updated)", "author": "Frank Herbert"}'

6.4.4. PATCH Requests#

curl -X PATCH http://localhost:5000/api/books/1 \
    -H "Content-Type: application/json" \
    -d '{"genre": "Sci-Fi Classic"}'

6.4.5. DELETE Requests#

curl -X DELETE http://localhost:5000/api/books/1