HTTP

Crystal HTTP Client

Making HTTP Requests

Crystal HTTP client uses HTTP::Client for API calls.

Introduction to Crystal HTTP Client

The Crystal HTTP client, provided by the HTTP::Client class, allows developers to easily perform HTTP requests in a Crystal application. This tutorial will guide you through making basic HTTP requests using Crystal's HTTP client and provide examples to facilitate a better understanding.

Setting Up Your Crystal Project

Before you start making HTTP requests, ensure that you have Crystal installed on your system. You can create a new Crystal project by running:

This creates a new directory named http_client_example with a basic project structure.

Making a Basic GET Request

To send a GET request using Crystal's HTTP client, you first need to require the HTTP module and then use the HTTP::Client class to perform the request.

In the above example, we instantiate the HTTP::Client with the base URL of the API. We then call the get method to fetch data from the /data endpoint and print the response body.

Handling HTTP Responses

The response object returned by the HTTP client contains several useful properties. You can access the status code, headers, and body. Here's how you can handle these in Crystal:

Making POST Requests

To make a POST request, you can use the post method of the HTTP::Client class. You need to pass the endpoint and the data you wish to send:

In this example, we send a JSON payload to the /submit endpoint. The second parameter specifies the content type, and the third parameter is the request body.

Error Handling in HTTP Requests

Handling errors is crucial for making robust HTTP requests. The Crystal HTTP client raises exceptions for network errors, which you can rescue using the begin and rescue blocks:

This code attempts to fetch data from the /data endpoint. If an error occurs, it is caught by the rescue block, and an error message is printed.

Previous
HTTP Server