http
A small HTTP client. Body-returning methods give back the response body as a string; head and status return the status code as an int. Import it with import http.
Looking for the built-in HTTP server?
http.serveis documented separately at /docs/http-server. This page covers the client functions.
Functions
| Function | Signature | Description |
|---|---|---|
get | http.get(url: string) → string | GET request, returns the response body |
post | http.post(url: string, body: string) → string | POST with a JSON body, returns the body |
put | http.put(url: string, body: string) → string | PUT with a JSON body, returns the body |
patch | http.patch(url: string, body: string) → string | PATCH with a JSON body, returns the body |
delete | http.delete(url: string) → string | DELETE request, returns the body |
head | http.head(url: string) → int | HEAD request, returns the status code |
status | http.status(url: string) → int | GET request, returns only the status code |
request | http.request(method: string, url: string, body: string, headers: string[]) → string | Generic request with custom "Key: Value" headers; returns the body |
post, put, and patch send Content-Type: application/json when the body is non-empty. request does the same unless you supply your own Content-Type header; pass "" as the body for methods that carry none.
Example
import http
// fetch a resource
let body = http.get("https://api.example.com/items")
print(body)
// post JSON
let created = http.post("https://api.example.com/items", "{\"name\":\"box\"}")
// check existence without downloading the body
if http.status("https://api.example.com/items/1") == 200 {
print("exists")
}
// custom method and headers
let result = http.request(
"DELETE",
"https://api.example.com/items/1",
"",
["Authorization: Bearer token123"],
)