Http
paket "http";
The http
package is used to make http requests. You will need this package to communicate with
an external API.
zahtjev
The zahtjev
function is used to make all kinds of http requests.
- takes:
- url - destination url for the request (
tekst
) - method - request method, HTTP verb, defaulted to
GET
if not provided - headers - request headers (
objekat
where all values aretekst
), optional - body - request body (
tekst
), optional
- url - destination url for the request (
- returns: response (
objekat
) - special cases:
- throws exception if url is invalid
- throws exception if method is not a valid HTTP verb
- throws exception if one of the headers is invalid (key or value)
The response object
Properties:
- status - response status (
broj
) - headeri - response headers (
objekat
) - tijelo - response body (
tekst
)
Example usage
Note that you will need functions from the JSON package.
var odgovor = zahtjev("https://catfact.ninja/fact"); ako(odgovor.status == 200){ var msg = odgovor.tijelo; var obj = objekatIzJSON(msg); ispis(obj.fact); }
Output: In just seven years, a single pair of cats and their offspring could produce a staggering total of 420,000 kittens.
The exact shape of the response body will vary from API to API. In this case, the catfact API provides an object with
the property fact
. Your API will probably behave differently.
Below is an example of how you might send a POST request:
var headers = {}; headers["Content-Type"] = "application/json"; var odgovor = zahtjev("https://httpbin.org/post", "POST", headers, JSONTekst({name: "Bosscript", extension: "boss"})); ako(odgovor.status == 200){ var msg = odgovor.tijelo; var obj = objekatIzJSON(msg); ispis(obj); }
Output: {name: "Bosscript", extension: "boss"}
In this case, we are sending a POST request to a simple echo server. Note that you need to set headers with the bracket syntax, because they contain hyphens.
var headers = { Content-Type: "application/json" }
Error: Unexpected token '-' @2:12