Fetching Data with Curl
One of the most common use cases for Curl is fetching data from a URL. Curl provides a simple and efficient way to retrieve data from web servers, APIs, and other online resources.
Basic Curl Usage
To fetch data from a URL using Curl, you can use the following basic command:
curl https://example.com
This will fetch the content of the specified URL and display it in the terminal. You can also save the output to a file using the -o
or -O
options:
## Save the output to a file named "example.html"
curl -o example.html https://example.com
## Save the output using the same filename as the URL
curl -O https://example.com/example.pdf
Handling HTTP Response Codes
Curl will return the HTTP response code of the request, which can be useful for debugging and error handling. You can display the response code using the -I
or -i
options:
## Display the response headers, including the status code
curl -I https://example.com
## Display the full response, including the status code
curl -i https://example.com
If the response code is not in the 2xx range (indicating a successful request), you can use Curl's exit codes to detect and handle errors in your scripts.
Handling Redirects
Curl can automatically follow redirects by using the -L
or --location
option. This is useful when the URL you're fetching has been moved or redirected to a different location.
curl -L https://example.com/moved
Handling Authentication
Curl can handle various types of authentication, such as Basic Authentication, Digest Authentication, and Bearer Token Authentication. You can provide the necessary credentials using the -u
or --user
options.
## Basic Authentication
curl -u username:password https://example.com
## Bearer Token Authentication
curl -H "Authorization: Bearer <token>" https://example.com/api
By combining these Curl features, you can fetch data from a wide range of online resources and handle various types of requests and responses.