HTTP Usage
Using the http
Module
The http
module has one function for every supported HTTP Method, shown below.
For more details, refer to the starlet
lib/http.
url = "http://localhost:8080/a/b?x=y&z=1"
# GET
http.get(url)
# PUT
http.put(url)
# POST
http.post(url)
# DELETE
http.delete(url)
# HEAD
http.head(url)
# OPTIONS
http.options(url)
# PATCH
http.patch(url)
Capture
For each http
method, adding the keyword parameter capture=True
will cause
the request and response to be captured. Subsequently, when run in association
with a sandbox, a diff between captures of baseline and sandbox will be
presented.
http.get(url, capture=True)
Headers
# also for other http methods
http.get(url, headers={"X-My-Header": "42"})
Query Parameters
You can include the query parameters in the URL, such as
http.get("http://localhost:8080/a/b?c=d&e=f")
or, as a parameter
http.get("http://localhost:8080", params={"c": "d"; "e": "f"})
Produce JSON Body
One can use the json
module to produce a JSON body to a request.
body = {
"field": "value",
"array": [1,2,3],
"bool": true
}
http.put(url, json_body=body)
# (also for other http methods)
JSON numbers are represented as Starlark ints when possible.
lst = [0.0, 1.01]
d = json.encode(lst)
lst2 = json.decode(d)
type(lst2[0]) # "int"
type(lst2[1]) # "float"
Consume JSON Body
resp = http.get(url)
v = resp.json()
# check type of JSON response
j = resp.json()
if type(j) == "dict":
# if the resp body is a JSON dict, then j is a dict
for k in j:
value = j[k]
pass
elif type(j) == "list":
for item in j:
pass
elif type(j) == "string":
pass
elif type(j) == "int":
pass
elif type(j) == "bool":
pass
elif type(j) == "float":
pass