Request():setHeader()
Set a new header for HTTP requests. This method allows you to add custom HTTP headers to your request before sending it.
Signature
setHeader(key: string, value: string): Request
Parameters
Parameters | Type | Description |
---|---|---|
key | string | The header name |
value | string | The header value |
Returns
Request
- Returns the Request object for method chaining
Description
The setHeader()
method adds a custom HTTP header to the request. Headers are metadata that provide additional information about the request, such as content type, authorization, or user agent. You can call this method multiple times to add multiple headers.
Examples
Setting Authorization Header
-- Add Bearer token for API authentication
local response = Request("https://api.example.com/data")
:setHeader("Authorization", "Bearer your-token-here")
:get()
Setting Content Type
-- Set JSON content type for POST requests
local response = Request("https://api.example.com/users")
:setHeader("Content-Type", "application/json")
:setParameter("name", "John Doe")
:setParameter("email", "john@example.com")
:post()
Multiple Headers
-- Set multiple headers for a request
local response = Request("https://api.example.com/protected")
:setHeader("Authorization", "Bearer token123")
:setHeader("Content-Type", "application/json")
:setHeader("Accept", "application/json")
:setHeader("User-Agent", "MyApp/1.0")
:get()
Custom Headers
-- Add custom application-specific headers
local response = Request("https://api.example.com/process")
:setHeader("X-API-Key", "your-api-key")
:setHeader("X-Request-ID", "unique-request-identifier")
:setHeader("X-Client-Version", "2.1.0")
:post()
Form Data Headers
-- Set headers for form data submission
local response = Request("https://example.com/login")
:setHeader("Content-Type", "application/x-www-form-urlencoded")
:setParameter("username", "user")
:setParameter("password", "pass")
:post()
Common HTTP Headers
Header Name | Typical Usage | Example |
---|---|---|
Authorization | Authentication tokens | "Bearer token123" |
Content-Type | Request body format | "application/json" |
Accept | Response format preference | "application/json" |
User-Agent | Client identification | "MyApp/1.0" |
X-API-Key | API authentication | "your-api-key" |
Content-Length | Request body size (usually set automatically) | "256" |
Notes
- Headers are case-insensitive, but it's conventional to use Header-Case (e.g.,
Content-Type
) - The method returns the Request object, allowing for method chaining
- Some headers may be automatically set by the HTTP client
- Certain headers like
Content-Length
are typically calculated automatically - Be careful with authentication headers and don't expose sensitive information
- You can override headers by setting the same header name multiple times