Net

network-related functions and helpers


Functions


The Net module provides functionality for network operations, including HTTP requests, file downloads, mail sending, and web serving capabilities.

Key Concepts

  • HTTP requests (GET, POST, PUT, PATCH, DELETE)
  • File downloads
  • Email sending
  • Web server functionality
  • Browser integration

Basic Usage

HTTP Requests

; basic GET request
response: request "https://api.example.com/data" ø
print response\body

; POST with JSON data
data: #[name: "John" age: 30]
response: request.post.json "https://api.example.com/users" data

; custom headers
response: request "https://api.example.com/data" .headers: #[
    authorization: "Bearer abc123"
    accept: "application/json"
] ø

; other HTTP methods
response: request.put "https://api.example.com/users/1" data
response: request.patch "https://api.example.com/users/1" data
response: request.delete "https://api.example.com/users/1" ø

Important
When making HTTP requests, always handle potential network errors and timeouts appropriately.

File Downloads

; download file
download "https://example.com/file.pdf"

; download with custom filename
download.as:"local.pdf" "https://example.com/file.pdf"

Sending Emails

; basic email
mail "recipient@email.com" "Hello!" "This is the message body"

; with custom SMTP configuration
mail .using: #[
        server: "smtp.company.com"
        port: 587
        username: "sender@company.com"
        password: "secret"
] "recipient@email.com" "Meeting reminder" "Don't forget our meeting tomorrow!" 

Opening URLs

; open URL in default browser
browse "https://arturo-lang.io"

Common Patterns

Simple REST API Client

define :apiClient [
    init: constructor [baseUrl token]

    headers: method [][
        #[
            authorization: join ["Bearer " \token]
            content-type: "application/json"
        ]
    ]

    get: method.distinct [endpoint][
        request join @[\baseUrl endpoint] .headers: \headers ø
    ]

    post: function [endpoint data][
        request.post.json join @[\baseUrl endpoint] .headers: \headers data
    ]
]

; create a new API Client
apiClient: to :apiClient ["https://api.example.com" ""]!

; usage
response: apiClient\get "/users"
newUser: apiClient\post "/users" #[name: "John" email: "john@email.com"]

Mini Web Server

; create a simple web server
; create a simple web server
serve.verbose [
    GET "/" [
        render.template {
            <html>
                <body>
                    <h1>Welcome!</h1>
                    <p>The time is: <||= now ||></p>
                </body>
            </html>
        }
    ]

    GET "/post/(?<id>.+)" $[id][
        render.template {
            This is post with id: <||= id ||>
        }
    ]

    GET "/styles/(?<file>.+)" $[file][
        ; serve static files
        read file
    ]
]

Tip
The serve function can also open Chrome in app mode with .chrome for a more app-like experience.