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
use std.net.http.Headers;
use std.net.http.client.{HttpClient, Request};
use std.net.http.OK;
struct Repo {
id: int,
name: string,
full_name: string,
// We can define the default value for the field.
// here is means the private default value is false.
private: bool = false,
html_url: string,
description: string,
}
const GITHUB_API = "https://api.github.com";
fn main() throws {
let client = HttpClient.new(default_headers: Headers.from_map({
"User-Agent": "Navi",
"Accept": "application/vnd.github.v3+json",
}));
let req = try Request.get(`${GITHUB_API}/repos/navi-language/navi`).set_query({
"t": "hello",
});
let res = try client.request(req);
if (res.status() != OK) {
println("Failed to fetch repo", try res.text());
return;
}
let repo = try res.json::<Repo>();
println(`${repo.name} - ${repo.description}`);
}In the above example, we send a GET request to the GitHub API to fetch the navi-language/navi repository information.
- We create a
HttpClientobject with default headers. TheUser-Agentheader is used to identify the client making the request. TheAcceptheader is used to specify the media type of the response that the client can understand. TheAcceptheader is set toapplication/vnd.github.v3+jsonto request the GitHub API to return the response in thev3version of the GitHub API. - We create a
Requestobject using theRequest.getmethod 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
Repostruct and print the repository name and description. We useResponse.jsonmethod on the Response type to parse the JSON response.This is same as
json.parsemethod, but it is more convenient to use.nv,use std.json; let repo = try json.parse::<Resp>(res.text()) - 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
navi - https://github.com/navi-language/naviNOTE
- The
Response.jsonmethod is a generic method, so you must specify the type by use::<T>syntax (This is the same asjson.parsemethod). - The
res.textandres.jsonmethods can throw an error, so you should use thetrykeyword to handle the error. - The response body is streamed, so you can't read it multiple times. The
textandjsonmethods are consuming the response body, so you can't call them multiple times.
Send a POST request
nv,no_run
use std.net.http.client.{HttpClient, Request};
use std.net.http.{Headers, Created};
use std.json;
struct Repo {
id: int,
name: string,
full_name: string,
private: bool = false,
html_url: string,
description: string,
}
struct CreateRepo {
org: string,
repo: string,
has_issues: bool,
}
fn main() throws {
let client = HttpClient.new();
let payload = CreateRepo {
org: "navi-language",
repo: "new-repo",
has_issues: true,
};
let req = try Request.post("https://api.github.com/repos")
.set_headers(Headers.from_map({
"Authorization": "Bearer <your-github-token>",
}))
.set_json(payload);
let res = try client.request(req);
if (res.status() != Created) {
println("Failed to create repo", try res.text());
return;
}
let repo = try res.json::<Repo>();
println(`Repo ${repo.name} created successfully`);
println(repo.html_url);
}As you see in the above example, we send a POST request to create a new repository on GitHub API.
- We create a
HttpClientobject. - We create a
CreateRepostruct to represent the request body. The struct contains the organization name, repository name, and whether the repository has issues enabled. - We create a
Requestobject using theRequest.postmethod and set the URL of the GitHub API. We set theAuthorizationheader to authenticate the request using a GitHub token. We set the request body using the Request.set_json method. Theset_jsonmethod serializes the struct to a JSON string and sets theContent-Typeheader toapplication/json. - If the request is successful, we parse the response JSON into a
Repostruct and print the repository name and URL. We use theResponse.jsonmethod on the Response type to parse the JSON response.