Skip to content

Send a HTTP request

The HttpClient object provides a HTTP client to send a HTTP request to a server.

Send a GET request

nv,no_run

In the above example, we send a GET request to the GitHub API to fetch the navi-language/navi repository information.

  • We create a HttpClient object with default headers. The User-Agent header is used to identify the client making the request. The Accept header is used to specify the media type of the response that the client can understand. The Accept header is set to application/vnd.github.v3+json to request the GitHub API to return the response in the v3 version of the GitHub API.
  • We create a Request object using the Request.get method and set the URL of the GitHub API. We also set the query parameters using the Request.set_query method. The query parameters are used to send additional data with the request.
  • If the request is successful, we parse the response JSON into a Repo struct and print the repository name and description. We use Response.json method on the Response type to parse the JSON response.

    This is same as json.parse method, but it is more convenient to use.

    nv,
  • If the request fails, we print the error message.

After running the program, you should see the repository name and description printed on the console.

txt

NOTE

  • The Response.json method is a generic method, so you must specify the type by use ::<T> syntax (This is the same as json.parse method).
  • The res.text and res.json methods can throw an error, so you should use the try keyword to handle the error.
  • The response body is streamed, so you can't read it multiple times. The text and json methods are consuming the response body, so you can't call them multiple times.

Send a POST request

nv,no_run

As you see in the above example, we send a POST request to create a new repository on GitHub API.

  • We create a HttpClient object.
  • We create a CreateRepo struct to represent the request body. The struct contains the organization name, repository name, and whether the repository has issues enabled.
  • We create a Request object using the Request.post method and set the URL of the GitHub API. We set the Authorization header to authenticate the request using a GitHub token. We set the request body using the Request.set_json method. The set_json method serializes the struct to a JSON string and sets the Content-Type header to application/json.
  • If the request is successful, we parse the response JSON into a Repo struct and print the repository name and URL. We use the Response.json method on the Response type to parse the JSON response.