Using cURL for API requests
Motivation
When building APIs, you need a way to send requests to test out what you are building. For big projects, tools like Postman or Insomnia are a great choice because they offer much more than just a way to send requests.
However, for small projects where all you need is a way to send requests to test your API, I find using cURL much more convenient.
Sending requests
GET and DELETE
If not specified differently, default HTTP method is GET.
To specify HTTP method, use -X
option.
POST, PUT and PATCH
For sending requests with data, use -d
flag.
If you are using -d
flag, request is by default treated as POST request, so you can omit -X
option.
Other useful configuration
Query parameters
When using query parameters, wrap the url in ""
to avoid potential problems.
Sending headers
To send request headers use -H
option.
curl -H "Authorization: Bearer <token>" http://localhost:8000/api/v1/todos
Reading response status and headers
To see information such as response status and response headers, use -i
flag.
When things gets messy
When you need to send a request with multiple headers and a long url, it can quickly become a burden to type everything. You can easily end up with something like this:
curl -i -X POST -H "Content-Type: application/json" -H "Authorization: Bearer <token>" -d @data.json http://localhost:8000/api/v1/todos
To avoid that, I recommend using a cli tool like endpoint.