Skip to content

Call an HTTP API

This program gets today’s temperature from a weather service and prints it.

<?nvs
// This program calls a weather API and reads its JSON reply.
// `Core\Test::answerHttp` gives a fixed reply for this address, so the program runs without
// a network. Delete this call to call the real API.
Core\Test::answerHttp('https://weather.example.com/today?city=Vienna', 200, {
body: '{"city":"Vienna","celsius":18}',
headers: ['Content-Type' => 'application/json'],
});
// `deadline` is the longest time the request may take.
Core\Http\Response $response = Core\Http\Client::get('https://weather.example.com/today?city=Vienna', { deadline: 5s });
if ($response->status() != 200) {
echo 'The weather service returned the status ', $response->status(), "\n";
} else {
// `jsonAs` reads the body into a shape with named fields. This prints `Vienna: 18 °C`.
var $today = $response->jsonAs<tainted { city: string, celsius: int }>();
echo $today->city, ': ', $today->celsius, " °C\n";
}
nvs run (CLI)
Vienna: 18 °C

This program runs with nvs run. It does not run under nvs serve.

Core\Test::answerHttp gives a fixed reply, so the program runs without a network. Delete that call to send the request to the real server.

Core\Http\Client::get sends a GET request and returns a Core\Http\Response. Check status() before you read the body. jsonAs reads the JSON body into the shape between < and >. The reply comes from another server, so the shape is tainted.

deadline is the longest time the request may take. Set it on every request, so a slow service does not make your own page slow.

Read Core\Http\Client for post, put and the other methods.