# 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.

Web page: https://pseudolearn.app/en/spec/biblioteca/http

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

## 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: Request and response**

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.

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`.

### Program: Asking for the weather

```pseudolearn
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**

```text
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.

> **Limit**
>
> - Only `http` or `https` URLs with an ASCII host and no credentials are allowed.
> - Redirects are not followed on their own: `redirected` builds the next request and, if the origin changes, drops every header whose name contains `auth`, `cookie`, `credential`, `key`, `passw`, `secret`, `session` or `token`.
> - Sizes and deadlines are limited by the host; `withResponseLimit` and `withTimeout` can only reduce them.

**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.

**See also**
- [11.4 Effects and capabilities](https://pseudolearn.app/en/spec/tareas/efectos.md)
- [11.2 Task scopes with Tasks and Spawn](https://pseudolearn.app/en/spec/tareas/ambitos.md)
