Skip to content

SpecificationXII · Library

12.9

HTTP

With the network capability, a program builds an HTTP request, sends it and receives a response with its status, headers and body.

Markdown version

12.9.1 How it works

  1. requestNetwork() gives a NetworkCap.
  2. HttpRequest(method, url) creates a request with an HttpMethod: GET, HEAD, POST, PUT, PATCH or DELETE. Requests are immutable: withHeader, withTextBody or withTimeout return a new request.
  3. network.send(request) returns Result<HttpResponse, IoError>.
Figure 12.9-1.The request goes out through the network capability and a response comes back. A 404 or a 500 are responses, not errors: only transport failures arrive as IoError.

The program sends a GET request to the server and receives a 200 response with its body. Responses, including 404 and 500, are Success; transport failures are Error.

ProgramAsking for the weather

Subroutine ConsultarClima() As Result<String, IoError>
  Define red As NetworkCap <- Propagate requestNetwork();
  Define peticion As HttpRequest <- HttpRequest(HttpMethod.GET, "https://clima.test/hoy");
  Define respuesta As HttpResponse <- Propagate red.send(peticion);
  Write "Estado: ", respuesta.status();
  Return respuesta.textBody();
EndSubroutine

Algorithm Clima
  Switch ConsultarClima() Do
    Success(texto): Write texto;
    Failure(problema): Write problema.code;
  EndSwitch
EndAlgorithm

Output

Estado: 200
Soleado, 25

The program finishes normally.

A response with a status from 100 to 599 is always Success; isSuccess() says whether it is between 200 and 299. Methods that can modify the server —POST, PUT, PATCH, DELETE— can end up in an uncertain state if the connection drops half-way: the program cannot know whether the change happened.

In short

  • requestNetwork, HttpRequest and send: capability, request and response.
  • HTTP statuses are responses; network failures are IoError.
  • Requests are immutable and the limits belong to the host.