Nyx by Example

HTTP POST

http_post(url, body) sends a POST request with Content-Type: text/plain. For custom headers and methods, use http_request(method, url, headers, body) which gives full control over the request.

Code

// HTTP POST request with a body

import "std/http"

fn main() -> int {
    let resp: Array = http_post("http://httpbin.org/post", "hello from Nyx")

    let status: int = http_status(resp)
    print("status: " + int_to_string(status))

    let body: String = http_body(resp)
    if body.length() > 200 {
        print("body (first 200 chars): " + body.substring(0, 200))
    } else {
        print("body: " + body)
    }

    // Custom headers and methods with http_request
    let headers: Array = ["Content-Type", "application/json"]
    let json_body: String = "{\"key\": \"value\"}"
    let resp2: Array = http_request("PUT", "http://httpbin.org/put", headers, json_body)
    print("PUT status: " + int_to_string(http_status(resp2)))

    return 0
}

Output

status: 200
body (first 200 chars): { "args": {}, "data": "hello from Nyx", ...}
PUT status: 200

Explanation

http_post is a convenience wrapper that sets Content-Type: text/plain. For JSON APIs, use http_request with explicit headers — the headers array uses a flat key-value format: ["Header-Name", "value", "Another", "value"].

http_request supports any HTTP method (GET, POST, PUT, DELETE, PATCH, etc.) and gives full control over headers and body content.

← Previous Next →

Source: examples/by-example/50-http-post.nx