Rest Rust Reference Documentation
Rest
Current Version: 11.6.1
Chilkat.Rest
Build REST requests with explicit paths, headers, query parameters,
request bodies, content types, and HTTP methods.
Connect once and send multiple requests over the same underlying
connection when appropriate.
Work with bearer tokens, OAuth2, AWS-style signing, Azure and Google
auth helpers, and other service-specific authentication patterns.
Send JSON, XML, text, binary data, form parameters, multipart requests,
streams, and file-based request bodies.
Read response bodies as strings, bytes, streams, JSON, XML, or
Use detailed error text, raw request generation, response headers,
connection state, and verbose diagnostics to troubleshoot API behavior.
For an extended overview, see
Rest Class Overview.
Build, send, authenticate, stream, and inspect REST API requests with precise control.
Chilkat.Rest is a flexible REST client class for applications
that need detailed control over request construction, connection reuse,
authentication, headers, query parameters, multipart bodies, streaming
uploads and downloads, response parsing, and low-level diagnostics. It is
especially useful for APIs where the application must carefully manage
provider-specific signing, request paths, body formats, and server responses.
Precise request construction
Connection reuse
Authentication support
Request bodies and multipart
Response handling
StringBuilder content, and inspect status codes and headers.
Diagnostics and debugging
Chilkat.Rest when you want fine-grained control over the
connection and request construction. For higher-level HTTP convenience
methods that accept full URLs directly, use Chilkat.Http. For
advanced socket routing, create the connection with Chilkat.Socket
and pass it to UseConnection.
Rest object
until they are replaced or cleared. When reusing an object for unrelated requests,
call the applicable Clear* methods rather than assuming request state
is automatically reset.
SendReq* call, call ReadResponseHeader and then read
the response body exactly once when a body is present. Fully consume the body before
sending another request on the same connection. A HEAD response has no
body; a 204 No Content response is represented by an empty body.
Rest class exposes redirect and response-header information but does
not automatically follow redirects or maintain a cookie jar. Applications should
process Location and Set-Cookie values explicitly when needed.
Object Creation
// Cargo.toml:
// [dependencies]
// chilkat = "11.6"
use chilkat::Rest;
// Once per process, before any other Chilkat call:
chilkat::unlock_bundle("Anything for 30-day trial")?; // shorthand for Global::new().unlock_bundle(..)
let rest = Rest::new();
// ... the native object is freed when `rest` goes out of scope.Creates the underlying native Chilkat object (Rest also implements Default). Every method takes &self, so the object never needs to be declared mut. A Rest is Send but not Sync: it may be moved to another thread, but a reference to it cannot be shared between threads at the same time.
The native object is freed when the Rest is dropped — when it goes out of scope, or explicitly with drop(rest). There is no Dispose method to call.
Errors
Methods that can fail return chilkat::Result<T>, which is Result<T, chilkat::Error>: a method whose only outcome is success or failure returns Result<()>, a method producing a string or an object returns Result<String> or Result<Rest>. The error carries the object's LastErrorText at the time of the failure (Error::last_error_text), the class and method names, and implements std::error::Error, so ? works in any function returning chilkat::Result or a Box<dyn Error>. Properties never fail, and methods that answer a question (has_..., is_..., ...) return a plain bool.
match rest.some_method(...) {
Ok(value) => println!("{value:?}"),
Err(e) => eprintln!("{}", e.last_error_text()),
}
Properties
AllowHeaderFolding
pub fn allow_header_folding(&self) -> bool
pub fn set_allow_header_folding(&self, value: bool)
Controls whether long request-header fields may be folded onto continuation lines. The default is false. When set to false, each request header is emitted on a single physical line.
false when the service requires unfolded header lines, as is common for canonicalized request signatures.AllowHeaderQB
pub fn allow_header_qb(&self) -> bool
pub fn set_allow_header_qb(&self, value: bool)
Controls whether non-ASCII request-header values may be converted to RFC 2047 encoded-word form using Q or Base64 encoding. The default is true.
Encoded words have forms such as =?utf-8?Q?...?= and =?utf-8?B?...?=. When this property is false, Chilkat does not apply this conversion.
Authorization
Gets or sets the value sent in the HTTP Authorization request header. Supply only the field value, such as Bearer eyJ..., not the text Authorization:.
SetAuth* method. A configured authentication provider may generate or replace the Authorization header when the request is sent.SetAuth* provider is active, its generated Authorization header takes precedence over this property and over a manually added Authorization header. ClearAuth clears both the provider and this value; clearing top-level headers also clears this property.ConnectFailReason
pub fn connect_fail_reason(&self) -> i32
After Connect fails, returns a code identifying the connection stage or TLS handshake stage that failed.
| Code | Meaning |
|---|---|
0 | Success |
1 | Empty hostname |
2 | DNS lookup failed |
3 | DNS timeout |
4 | Aborted by the application |
5 | Internal failure |
6 | Connection timed out |
7 | Connection rejected or otherwise failed |
99 | Chilkat is not unlocked or the trial expired |
TLS-related codes:
| Code | Meaning |
|---|---|
100 | TLS internal error |
101 | Failed to send ClientHello |
102 | Unexpected handshake message |
103 | Failed to read ServerHello |
104 | No server certificate |
105 | Unexpected TLS protocol version |
106 | Server certificate verification failed |
107 | Unacceptable TLS protocol version |
109 | Failed to read handshake messages |
110 | Failed to send the client-certificate handshake message |
111 | Failed to send ClientKeyExchange |
112 | Client certificate private key is inaccessible |
113 | Failed to send CertificateVerify |
114 | Failed to send ChangeCipherSpec |
115 | Failed to send Finished |
116 | The server Finished message is invalid |
LastErrorText for the full failure context.Connect resets this property to 0. HTTP response properties are separate and are not cleared by a later failed connection attempt.ConnectTimeoutMs
pub fn connect_timeout_ms(&self) -> i32
pub fn set_connect_timeout_ms(&self, value: i32)
Gets or sets the maximum number of milliseconds to wait for the remote server to accept the TCP connection. This timeout covers connection establishment, not the later sending or receiving of HTTP data.
IdleTimeoutMs to control how long an established operation may remain without send or receive progress.The default is 30000 milliseconds.
DebugLogFilePath
pub fn debug_log_file_path(&self) -> String
pub fn set_debug_log_file_path(&self, value: &str)
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
DebugMode
pub fn debug_mode(&self) -> bool
pub fn set_debug_mode(&self, value: bool)
When true, calls to the Send* and FullRequest* methods compose the complete request but do not transmit it. Retrieve the generated request with GetLastDebugRequest. The default is false.
In debug mode, a composed full-request call reports a synthetic successful result with ResponseStatusCode equal to 201, ResponseStatusText equal to OK, and no actual response header or response body.
EnableSecrets
pub fn enable_secrets(&self) -> bool
pub fn set_enable_secrets(&self, value: bool)
Controls automatic resolution of credentials from operating-system secure storage. The default is false.
When set to true, supported credential inputs may contain a secret specification beginning with !! instead of a literal secret. Chilkat resolves the specification from Windows Credential Manager on Windows or Apple Keychain on macOS.
The specification format is:
!![appName|]service[|domain]|username
For this class, secret specifications apply to the username and password supplied to SetAuthBasic.
HeartbeatMs
pub fn heartbeat_ms(&self) -> i32
pub fn set_heartbeat_ms(&self, value: i32)
Controls the interval, in milliseconds, between AbortCheck event callbacks during supported long-running operations. The default is 0, which disables periodic AbortCheck callbacks.
Host
Gets or sets the value of the HTTP Host request header.
Connect or UseConnection. Set this property explicitly only when the request must present a different virtual-host value.An explicitly assigned value overrides the generated HTTP Host field, but it does not change the TCP/TLS destination established by Connect or UseConnection.
IdleTimeoutMs
pub fn idle_timeout_ms(&self) -> i32
pub fn set_idle_timeout_ms(&self, value: i32)
Gets or sets the maximum number of milliseconds to wait when a send or receive operation has stopped making progress. The default is 30000 milliseconds.
A value of 0 disables the inactivity timeout.
LastErrorHtml
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
pub fn last_method_success(&self) -> bool
pub fn set_last_method_success(&self, value: bool)
Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
LastRedirectUrl
Returns the redirect target from the most recently received response. The value comes from the response Location header. If the most recent response was not a redirect or did not contain a Location header, this property is empty.
Rest does not automatically follow the redirect; send a new request explicitly, reconnecting first if the target host changes.LastRequestHeader
Returns the HTTP header fields from the most recently composed request, excluding the request line. The request line is available separately in LastRequestStartLine.
A failed Connect does not clear this value. It continues to describe the last request that was composed and sent.
LastRequestStartLine
Returns the request line from the most recently composed request. It contains the HTTP method, request target, and HTTP version, for example:
GET /v1/items?limit=10 HTTP/1.1
A failed Connect does not clear this value. It continues to describe the last request that was composed and sent.
NumResponseHeaders
pub fn num_response_headers(&self) -> i32
Returns the number of response header field occurrences. Enumerate them with zero-based indexes using ResponseHdrName and ResponseHdrValue.
A failed Connect does not reset this count; it remains the count for the last received HTTP response.
PartSelector
Selects the multipart entity or part targeted by multipart-building operations such as AddHeader, RemoveHeader, and the SetMultipartBody* methods.
| Value | Selected target |
|---|---|
(empty) | The top-level request entity |
0 | The top-level request entity |
1 | The first multipart subpart |
2 | The second multipart subpart |
1.2 | The second child within the first subpart |
The value 0, like the empty string, selects the top-level request entity. A nonnumeric selector is invalid. A body assignment can create a higher-numbered part even when lower-numbered parts do not yet exist.
PercentDoneOnSend
pub fn percent_done_on_send(&self) -> bool
pub fn set_percent_done_on_send(&self, value: bool)
Applies to the full-request methods that both upload a request and download a response. It selects which direction is represented by percent-complete events.
false(default): progress refers to receiving the response body.true: progress refers to sending the request body.
ResponseHeader
Returns the HTTP response header fields from the most recently received response, excluding the status line.
ResponseStatusCode and ResponseStatusText.Repeated fields remain separate and in received order. The field-name casing is preserved. A failed Connect does not clear this value; it continues to describe the last received HTTP response.
ResponseStatusCode
pub fn response_status_code(&self) -> i32
Returns the numeric HTTP status code from the most recently received response, such as 200, 404, or 503.
400 or 404 is still a completed HTTP exchange. Inspect ResponseStatusCode and the response body to determine the API-level result.Connect does not clear this property. It continues to report the status of the last HTTP response that was actually received.ResponseStatusText
Returns the reason phrase associated with the most recently received HTTP status code, such as OK or Not Found.
Connect does not clear this property; it remains associated with the last received HTTP response.StreamNonChunked
pub fn stream_non_chunked(&self) -> bool
pub fn set_stream_non_chunked(&self, value: bool)
Controls whether streaming uploads use a Content-Length header instead of HTTP/1.1 chunked transfer encoding when the total body size is known. The default is true.
When true and the stream length can be determined—for example, a file stream—Chilkat sends a non-chunked request. When false, Chilkat uses Transfer-Encoding: chunked. If the stream length is unknown, chunked transfer may still be required.
UncommonOptions
pub fn uncommon_options(&self) -> String
pub fn set_uncommon_options(&self, value: &str)
Provides opt-in compatibility settings for uncommon requirements. The default is the empty string. Supply one or more comma-separated keywords:
| Keyword | Effect |
|---|---|
AllowDuplicateQueryParams | Allows AddQueryParam to append another parameter having the same name instead of replacing the existing one. |
AllowInsecureBasicAuth | Allows Basic authentication over a non-TLS remote connection. By default, Basic authentication is allowed only over TLS, an SSH tunnel, or localhost. |
DisableTls13 | Disables TLS 1.3 so negotiation is limited to TLS 1.2 or earlier supported versions. |
ProtectFromVpn | On Android, attempts to bypass an installed or active VPN for this connection. |
VerboseLogging
pub fn verbose_logging(&self) -> bool
pub fn set_verbose_logging(&self, value: bool)
If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
Methods
AddHeader
Adds an HTTP request header using name as the field name and value as the field value. If a request header with the same name is already present for the selected part, its value is replaced.
name—for example, Content-Type—and not the trailing colon. For multipart requests, PartSelector determines whether the header is added to the top-level request or to a MIME part.Request headers persist across requests until removed or cleared. Adding the same header again replaces its current value.
PartSelector. Use an empty selector or 0 for top-level request headers; select a part before adding that part's headers.Returns Ok(()) for success, Err(chilkat::Error) for failure.
AddMwsSignature
Computes the Amazon Marketplace Web Service (MWS) request signature using the secret key in mws_secret_key and adds or replaces the Signature query parameter. Call this after all other MWS request parameters have been added.
http_verb is the HTTP method, uri_path is the MWS resource path, and domain is the request domain. http_verb and uri_path should match the values used by the request-sending method. The method also adds or replaces the Timestamp parameter using the current system time.
SetAuthAws.Returns Ok(()) for success, Err(chilkat::Error) for failure.
AddPathParam
Adds or replaces a path-substitution parameter. Before a request is sent, occurrences of name in the supplied request path are replaced by value.
For example, setting name to fileId and value to abc123 transforms /drive/v3/files/fileId into /drive/v3/files/abc123.
name; braces are not required unless they are part of the placeholder text you choose.Matching is case-sensitive and literal. Every occurrence of name is replaced, substitutions are applied in the order they were added, and replacement applies to the entire uriPath string, including any query portion.
/, ?, and # remain delimiters, and existing percent escapes are preserved. Percent-encode reserved characters before calling this method when they are intended to be data.Path substitutions persist across requests until replaced or removed with ClearAllPathParams.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AddQueryParam
Adds or replaces a query-string parameter using name as the parameter name and value as its value. The stored query parameters are incorporated into the request target when a request is sent.
tag=red&tag=blue, include AllowDuplicateQueryParams in UncommonOptions.name and value are unencoded text. Chilkat percent-encodes the parameter name and value when composing the request target. For example, a space becomes %20, a literal plus sign becomes %2B, and a literal percent sign becomes %25. Existing percent escapes supplied to this method are therefore encoded again. Parameters persist across ordinary requests until removed or cleared.Parameter names are case-sensitive. Adding the same exact name again replaces the existing value unless AllowDuplicateQueryParams is enabled in UncommonOptions.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AddQueryParams
Adds multiple query parameters from the query-string text in query_string. Use the form field1=value1&field2=value2&field3=value3.
query_string must already be percent-encoded as required for a URL query string. Do not include a leading ?. For individual name/value pairs, AddQueryParam is usually clearer.The input is parsed as an already URL-encoded query string and then normalized when the request is composed. A plus sign is interpreted as a space and is emitted as %20; encoded delimiters such as %26 remain data; an item without an equals sign is treated as a parameter with an empty value.
Parameters added by this method persist across ordinary requests. When ARG2 of a request method already contains a query string, those inline parameters appear first, followed by the parameters stored in the Rest object.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
AddQueryParamSb
Adds or replaces a query-string parameter named by name. The parameter value is read from the StringBuilder in value.
AllowDuplicateQueryParams in UncommonOptions to retain repeated names.name and the text in value are unencoded text. Chilkat percent-encodes the parameter name and value when composing the request target. For example, a space becomes %20, a literal plus sign becomes %2B, and a literal percent sign becomes %25. Existing percent escapes supplied to this method are therefore encoded again. Parameters persist across ordinary requests until removed or cleared.Parameter names are case-sensitive. Adding the same exact name again replaces the existing value unless AllowDuplicateQueryParams is enabled in UncommonOptions.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ClearAllHeaders
Removes all HTTP request headers previously added to this object.
The method clears headers only from the entity selected by PartSelector. Clearing top-level headers also clears the Authorization property. Automatically generated fields such as Host and Content-Length may be added again when the next request is composed.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ClearAllParts
Removes all multipart subparts from the request under construction. This is useful when reusing the same REST object after sending a multipart request.
This also resets PartSelector to the empty string and releases the configured multipart bodies and part streams.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ClearAllPathParams
Removes all path-substitution parameters previously added with AddPathParam.
After clearing, placeholder text in later request paths is sent unchanged.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ClearAllQueryParams
Removes all query parameters previously added to this object.
This clears the stored query/form parameter collection. It does not remove a query string written directly in the uriPath argument of a request method.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ClearAuth
Clears authentication providers and credentials previously configured through this class's SetAuth* methods.
This removes the active authentication provider and clears the manually configured Authorization value.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ClearResponseBodyStream
Clears the response-stream destination previously configured by SetResponseBodyStream. Subsequent full-request methods return or store the response body normally instead of streaming it to that destination.
Clearing the destination does not alter the Stream object itself.
Connect
Establishes the initial TCP connection to the REST server. hostname is a DNS hostname or an IPv4/IPv6 address, port is the server port, and tls specifies whether the connection uses TLS. Common combinations are port 80 with tls set to false, and port 443 with tls set to true.
If auto_reconnect is true, subsequent requests may automatically reconnect when the existing connection is no longer usable. If auto_reconnect is false, a lost connection causes the request to fail until the application explicitly reconnects.
hostname is not a URL. For https://api.example.com/v1/items, pass api.example.com. The request path is supplied separately to the request method.Connect is intended for a direct connection. For HTTP or SOCKS proxies, SSH tunneling, client certificates, custom socket routing, or other advanced connection setup, establish a connected Socket and pass it to UseConnection.auto_reconnect is true, Chilkat can establish a new connection before a later request after the previous connection has closed. This option should not be interpreted as a promise to replay a request that failed after transmission began.ConnectFailReason to 0. A failed Connect does not clear the HTTP response and last-request properties from an earlier completed exchange; those properties continue to describe the last HTTP request/response, not the failed connection attempt.Returns Ok(()) for success, Err(chilkat::Error) for failure.
Disconnect
Closes the current HTTP connection, if one is open. max_wait_ms is the maximum number of milliseconds to wait while attempting a clean shutdown.
UseConnection, calling Disconnect also disconnects that Socket. If automatic reconnection was enabled, a later request may reconnect it.Returns Ok(()) for success, Err(chilkat::Error) for failure.
FullRequestBd
Sends a complete request whose binary body is read from the BinData in bin_data. The text response body replaces the existing contents of the StringBuilder in response_body.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.400 or 404 is still a completed HTTP exchange. Inspect ResponseStatusCode and the response body to determine the API-level result.response_body is cleared and replaced with the textual response body.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
FullRequestFormUrlEncoded
Sends a complete application/x-www-form-urlencoded request. The form body is built from the parameters previously added with AddQueryParam or AddQueryParams. The request Content-Type is set to application/x-www-form-urlencoded. The response body is read as text and returned.
This convenience method performs the equivalent of SendReqFormUrlEncoded, ReadResponseHeader, and ReadRespBodyString in sequence.
For full-request methods, PercentDoneOnSend selects whether percent-complete events refer to sending the request body or receiving the response body.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.400 or 404 is still a completed HTTP exchange. Inspect ResponseStatusCode and the response body to determine the API-level result.Parameters written directly in uri_path remain in the URL query string. Parameters stored through AddQueryParam, AddQueryParamSb, or AddQueryParams are encoded into the form body. After the form request is sent, this stored parameter collection is cleared.
Content-Type to application/x-www-form-urlencoded. That request-header value remains configured for later requests until it is replaced or cleared.Returns Err(chilkat::Error) on failure.
FullRequestMultipart
Sends a complete multipart request using the parts and part headers configured through PartSelector, AddHeader, and the multipart-body methods. The response body is read as text and returned.
This convenience method performs the equivalent of SendReqMultipart, ReadResponseHeader, and ReadRespBodyString in sequence.
For full-request methods, PercentDoneOnSend selects whether percent-complete events refer to sending the request body or receiving the response body.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.400 or 404 is still a completed HTTP exchange. Inspect ResponseStatusCode and the response body to determine the API-level result.multipart/form-data.The request fails if no multipart subparts are configured.
Returns Err(chilkat::Error) on failure.
FullRequestNoBody
Sends a complete request with no request body. The response body is read as text and returned.
This convenience method performs the equivalent of SendReqNoBody, ReadResponseHeader, and ReadRespBodyString in sequence.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.400 or 404 is still a completed HTTP exchange. Inspect ResponseStatusCode and the response body to determine the API-level result.Returns Err(chilkat::Error) on failure.
FullRequestNoBodyBd
Sends a complete request without a request body and stores the binary response body in the BinData in bin_data, replacing its previous contents.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.400 or 404 is still a completed HTTP exchange. Inspect ResponseStatusCode and the response body to determine the API-level result.bin_data is cleared and replaced with the binary response body.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
FullRequestNoBodySb
Sends a complete request without a request body and stores the text response body in the StringBuilder in sb, replacing its previous contents.
This is the StringBuilder form of FullRequestNoBody.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.400 or 404 is still a completed HTTP exchange. Inspect ResponseStatusCode and the response body to determine the API-level result.sb is cleared and replaced with the textual response body.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
FullRequestSb
Sends a complete request whose text body is read from the StringBuilder in request_body. The text response body replaces the existing contents of the StringBuilder in response_body.
This is the StringBuilder form of FullRequestString.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.400 or 404 is still a completed HTTP exchange. Inspect ResponseStatusCode and the response body to determine the API-level result.Content-Type header; add the media type required by the API, such as application/json; charset=utf-8.response_body is cleared and replaced with the response body.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
FullRequestStream
Sends a complete request whose body is read from the Stream in stream. Streaming is appropriate for large uploads because the entire request body need not be held in memory. The response body is read as text and returned.
This convenience method performs the equivalent of SendReqStreamBody, ReadResponseHeader, and ReadRespBodyString in sequence.
For full-request methods, PercentDoneOnSend selects whether percent-complete events refer to sending the request body or receiving the response body.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.400 or 404 is still a completed HTTP exchange. Inspect ResponseStatusCode and the response body to determine the API-level result.Returns Err(chilkat::Error) on failure.
FullRequestString
Sends a complete request whose text body is supplied in body_text, such as JSON, XML, or plain text. The response body is read as text and returned.
This convenience method performs the equivalent of SendReqStringBody, ReadResponseHeader, and ReadRespBodyString in sequence.
For full-request methods, PercentDoneOnSend selects whether percent-complete events refer to sending the request body or receiving the response body.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.400 or 404 is still a completed HTTP exchange. Inspect ResponseStatusCode and the response body to determine the API-level result.Content-Type header; add the media type required by the API, such as application/json; charset=utf-8.Returns Err(chilkat::Error) on failure.
GetLastDebugRequest
Copies the fully composed HTTP request generated while DebugMode was true into the BinData in bd. The captured data includes the request line, headers, and body that would have been sent.
bd is cleared and replaced. The captured bytes are the complete composed HTTP/1.1 request, including chunk framing when a streaming request uses Transfer-Encoding: chunked.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
GetLastJsonData
Copies operation-specific diagnostic or result information from the most recently completed method into the JsonObject in json. Many methods do not produce additional JSON details, in which case the object is empty.
ReadRespBd
Reads the response body as raw bytes into the BinData in response_body, replacing its previous contents. Call this after ReadResponseHeader.
HEAD response. A 204 No Content response is handled as a successful empty body.Returns Ok(()) for success, Err(chilkat::Error) for failure.
ReadRespBodyStream
Reads the response body into the Stream supplied in stream. Call this after ReadResponseHeader.
If auto_set_stream_charset is true and the response is textual, the stream's StringCharset is set from the charset parameter in the response Content-Type header when one is present. auto_set_stream_charset has no effect for binary responses.
HEAD response. A 204 No Content response is handled as a successful empty body.Returns Ok(()) for success, Err(chilkat::Error) for failure.
ReadRespBodyString
Reads the response body as text and returns it. Call this only after ReadResponseHeader has returned the response status code.
ReadRespBd or ReadRespBodyStream for binary or very large content.HEAD response. A 204 No Content response is handled as a successful empty body.Returns Err(chilkat::Error) on failure.
ReadRespChunkBd
After ReadResponseHeader has been called, reads the next chunk of the response body and appends the received bytes to the BinData in bd. The call waits until at least min_size bytes are available, unless the response ends first. The final chunk may contain fewer than min_size bytes, including zero bytes.
| Return value | Meaning |
|---|---|
-1 | The read failed; inspect LastErrorText. |
0 | The remaining response bytes were returned and the response body is complete. |
1 | A chunk was returned and more response bytes remain. |
ReadResponseHeader
Reads the HTTP response status line and header fields. The returned integer is the HTTP status code, such as 200, 404, or 500. A return value of -1 means that no HTTP response was received because a transport or protocol error occurred.
After this method returns a status code, inspect ResponseHeader, ResponseStatusCode, ResponseStatusText, and the response-header access methods. If the response has a body, read it with ReadRespBodyString, ReadRespBd, ReadRespBodyStream, or another appropriate body-reading method.
HEAD response. A 204 No Content response is handled as a successful empty body.ReadRespSb
Reads the response body as text into the StringBuilder in response_body, replacing its previous contents. Call this after ReadResponseHeader.
HEAD response. A 204 No Content response is handled as a successful empty body.Returns Ok(()) for success, Err(chilkat::Error) for failure.
RemoveHeader
Removes all request headers named by name from the request level selected by PartSelector.
Header-name matching is case-insensitive, and all matching occurrences are removed.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
RemoveQueryParam
Removes all query parameters whose name matches name.
Parameter-name matching is case-sensitive. All parameters having the exact name are removed. A true return value indicates that the operation completed successfully; it does not guarantee that a matching parameter existed.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
ResponseHdrByName
Returns the value of the response header field named by name. HTTP header field names are case-insensitive.
NumResponseHeaders, ResponseHdrName, and ResponseHdrValue to enumerate every field occurrence.If the response contains the same field more than once, this method returns the first matching value. Enumerate the header collection to obtain all occurrences, especially for fields such as Set-Cookie.
Returns Err(chilkat::Error) on failure.
ResponseHdrName
Returns the field name of the response header at zero-based index index. Valid indexes range from 0 through NumResponseHeaders minus one.
Enumeration preserves the response-field order and the field-name casing received from the server. Repeated fields occupy separate indexes.
Returns Err(chilkat::Error) on failure.
ResponseHdrValue
Returns the field value of the response header at zero-based index index. Use the same index with ResponseHdrName to obtain the corresponding field name.
Repeated response fields occupy separate indexes and are returned in received order.
Returns Err(chilkat::Error) on failure.
SendReqBd
Sends a request whose binary body is read from the BinData in body.
http_verb is the HTTP method, such as GET, POST, or PUT. uri_path is the request path. This is a low-level send operation: after it succeeds, call ReadResponseHeader and then read the response body with the appropriate response method.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.Returns Ok(()) for success, Err(chilkat::Error) for failure.
SendReqFormUrlEncoded
Sends an application/x-www-form-urlencoded request. The request body is built from the parameters added with AddQueryParam or AddQueryParams. Any manually supplied Content-Type value is replaced with application/x-www-form-urlencoded.
http_verb is the HTTP method, such as GET, POST, or PUT. uri_path is the request path. This is a low-level send operation: after it succeeds, call ReadResponseHeader and then read the response body with the appropriate response method.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.Parameters written directly in uri_path remain in the URL query string. Parameters stored through AddQueryParam, AddQueryParamSb, or AddQueryParams are encoded into the form body. After the form request is sent, this stored parameter collection is cleared.
Content-Type to application/x-www-form-urlencoded. That request-header value remains configured for later requests until it is replaced or cleared.Returns Ok(()) for success, Err(chilkat::Error) for failure.
SendReqMultipart
Sends a multipart request using the parts configured with PartSelector, AddHeader, and the multipart-body methods.
http_verb is the HTTP method, such as GET, POST, or PUT. uri_path is the request path. This is a low-level send operation: after it succeeds, call ReadResponseHeader and then read the response body with the appropriate response method.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.multipart/form-data.The request fails if no multipart subparts are configured.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SendReqNoBody
Sends a request without a request body.
http_verb is the HTTP method, such as GET, POST, or PUT. uri_path is the request path. This is a low-level send operation: after it succeeds, call ReadResponseHeader and then read the response body with the appropriate response method.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.Returns Ok(()) for success, Err(chilkat::Error) for failure.
SendReqSb
Sends a request whose text body is read from the StringBuilder in body_sb. Set the request Content-Type header to identify the body format.
http_verb is the HTTP method, such as GET, POST, or PUT. uri_path is the request path. This is a low-level send operation: after it succeeds, call ReadResponseHeader and then read the response body with the appropriate response method.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.Content-Type header; add the media type required by the API, such as application/json; charset=utf-8.Returns Ok(()) for success, Err(chilkat::Error) for failure.
SendReqStreamBody
Sends a request whose body is read from the Stream in stream. The stream may supply text or binary data; set the request Content-Type header as required by the API.
http_verb is the HTTP method, such as GET, POST, or PUT. uri_path is the request path. This is a low-level send operation: after it succeeds, call ReadResponseHeader and then read the response body with the appropriate response method.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.Returns Ok(()) for success, Err(chilkat::Error) for failure.
SendReqStringBody
Sends a request whose text body is supplied in body_text, such as JSON, XML, form-independent text, or another textual representation. Set the request Content-Type header to identify the body format expected by the server.
http_verb is the HTTP method, such as GET, POST, or PUT. uri_path is the request path. This is a low-level send operation: after it succeeds, call ReadResponseHeader and then read the response body with the appropriate response method.
uri_path is the path and optional query portion of the URL, not a complete URL. For https://api.example.com/v1/items?limit=10, pass /v1/items?limit=10. The server name and port are established separately by Connect or UseConnection.Content-Type header; add the media type required by the API, such as application/json; charset=utf-8.Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetAuthAws
Associates the AuthAws provider in auth_provider with this REST object. Chilkat uses the provider to sign each AWS request after the request method, path, query parameters, headers, and body are known. The application does not need to construct the Authorization header manually.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetAuthAzureSas
Associates the AuthAzureSAS provider in auth_provider with this REST object. Chilkat automatically adds an Authorization: SharedAccessSignature ... header to subsequent requests.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetAuthAzureStorage
Associates the AuthAzureStorage provider in auth_provider with this REST object. Chilkat automatically applies the Azure Storage authorization information required for each request.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetAuthBasic
Configures HTTP Basic authentication using username as the username and password as the password. Chilkat automatically generates an Authorization: Basic ... header for subsequent requests.
AllowInsecureBasicAuth in UncommonOptions exists only for exceptional compatibility needs.Some APIs use an account ID, client ID, API key, token, or secret in place of a traditional username or password; follow the service documentation.
Authorization header when each request is composed and takes precedence over a value set through the Authorization property or AddHeader.Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetAuthBasicSecure
Configures HTTP Basic authentication using the SecureString objects in username and password for the username and password. The resulting request behavior is the same as SetAuthBasic.
SecureString reduces unnecessary exposure of the credential text in ordinary application strings. Basic authentication must still be protected by TLS.Authorization header when each request is composed and takes precedence over a manually configured Authorization value.Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetAuthGoogle
Associates the AuthGoogle provider in auth_provider with this REST object. Chilkat uses the provider to add the Google authentication information needed by subsequent API requests.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetAuthOAuth1
Associates the OAuth1 provider in auth_provider with this REST object for OAuth 1.0 or OAuth 1.0a request signing.
If use_query_params is true, the OAuth parameters and signature are placed in the query string. If use_query_params is false, they are placed in the Authorization header.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetAuthOAuth2
Associates the OAuth2 provider in auth_provider with this REST object. The provider must contain a valid access token. Chilkat then adds an Authorization: Bearer <access-token> header to each request.
The access token may be obtained through an OAuth flow or loaded from previously saved token data. Token acquisition, refresh, expiration, and scope requirements are determined by the authorization server.
AddHeader. Do not configure both approaches for the same request because they compete for the same Authorization header.OAuth2 object is consulted when each request is composed rather than copied at setup time. Keep it alive while the Rest object uses it. Changing its AccessToken changes the bearer token used by subsequent requests.Authorization value.Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetMultipartBodyBd
Sets the binary body of the multipart part identified by PartSelector from the BinData in body_data.
Setting the body creates the selected part when it does not already exist. Part numbers do not need to be created consecutively.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetMultipartBodySb
Sets the text body of the multipart part identified by PartSelector from the StringBuilder in body_sb.
Setting the body creates the selected part when it does not already exist. Part numbers do not need to be created consecutively.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetMultipartBodyStream
Uses the Stream in stream as the body source for the multipart part identified by PartSelector.
Stream object alive. It is read from its current position and must be reset before reusing it for another upload.Setting the body creates the selected part when it does not already exist. Part numbers do not need to be created consecutively.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetMultipartBodyString
Sets the text body of the multipart part identified by PartSelector to body_text.
AddHeader while the part is selected to set its Content-Type, Content-Disposition, and other part headers.Setting the body creates the selected part when it does not already exist. Part numbers do not need to be created consecutively.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
SetResponseBodyStream
Configures a Stream destination for response bodies received by the full-request convenience methods. The body is written to response_stream only when the response status code matches expected_status.
If streaming occurs successfully, a string-returning full-request method returns OK. If streaming was selected but writing the body fails, it returns FAIL. If the status code does not match expected_status, the body is not streamed and remains available as the method's normal response text.
If auto_set_stream_charset is true and the response is textual, the destination stream's StringCharset is set from the response Content-Type charset when available. auto_set_stream_charset is ignored for binary responses.
expected_status value | Status codes that are streamed |
|---|---|
200 | Only 200 |
-200 | 200 through 299 |
-210 | 210 through 219 |
ClearResponseBodyStream to restore normal response-body handling.For Boolean-returning full-request methods, successful streaming returns true. A StringBuilder response output receives OK; a BinData response output is cleared. If the status does not match expected_status, the stream is not written and the method returns the response through its normal output.
The configuration remains active for later full-request calls until ClearResponseBodyStream is called.
Returns Ok(()) for success, Err(chilkat::Error) for failure.
UseConnection
Uses the already-connected Socket in connection as the transport for REST requests. The socket may represent a direct TCP or TLS connection, an HTTP or SOCKS proxy connection, an SSH-tunneled channel, or another connection configured through the Socket API.
auto_reconnect controls automatic reconnection for later requests when the connection is no longer usable.
Connect for ordinary direct connections. Use UseConnection when the connection requires advanced Socket configuration.Rest object retains and operates on the supplied Socket. Keep the Socket object alive while it is attached. Calling Disconnect disconnects it; with auto_reconnect set to true, a later request can reconnect the same Socket object.Returns Ok(()) for success, Err(chilkat::Error) for failure.
Events
All Chilkat methods are synchronous: the call returns when the work is done. During a call, Rest raises three events so your application can show progress and offer a way out. Implement the chilkat::EventHandler trait (every method has a do-nothing default, so implement only the events you need) and install it with set_event_handler:
use chilkat::{Rest, EventHandler};
struct Progress;
impl EventHandler for Progress {
fn percent_done(&mut self, pct: i32) -> bool {
println!("{pct}%");
false // return true to abort the method in progress
}
fn progress_info(&mut self, name: &str, value: &str) {
println!("{name}: {value}");
}
}
let rest = Rest::new();
rest.set_event_handler(Progress);
rest.set_heartbeat_ms(250); // raise abort_check 4 times per second during Chilkat callsFor a one-off handler the closure methods avoid writing a type; they may be combined, and each replaces the previously set closure for that one event (installing a closure removes a trait handler set earlier, and vice versa):
rest.on_percent_done(|pct| { println!("{pct}%"); false });
rest.on_progress_info(|name, value| println!("{name}: {value}"));Installs handler as the receiver of this object's events, replacing any handler or closures set earlier. The object owns the handler, which must be Send + 'static.
Removes the handler and any closures; events are no longer delivered.
AbortCheck fires at regular intervals controlled by the HeartbeatMs property (0, the default, disables it); PercentDone fires when an operation's completion percentage is known; ProgressInfo delivers named progress values. Returning true from abort_check or percent_done aborts the running method, which then returns Err.
Events fire on the thread that called the method, before that method returns. A panic inside a handler aborts the running method and is re-raised to the caller once the native library has returned, so it never unwinds through C frames. To abort a long operation from another thread, share an Arc<AtomicBool> with an abort_check handler, or set the object's AbortCurrent property to true.
AbortCheck
fn abort_check(&mut self) -> bool
Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the HeartbeatMs property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.
Example (closure form; the EventHandler trait method is equivalent):
rest.set_heartbeat_ms(250); // call abort_check 4 times per second
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = stop.clone();
rest.on_abort_check(move || flag.load(std::sync::atomic::Ordering::Relaxed));
// ... another thread may now abort the method in progress with stop.store(true, Ordering::Relaxed)PercentDone
fn percent_done(&mut self, pct: i32) -> bool
This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pct_done argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pct_done equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).
The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.
To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.
Example (closure form; the EventHandler trait method is equivalent):
rest.on_percent_done(|pct| {
// pct ranges from 1 to 100.
println!("Percent done: {pct}");
false // return true to abort the method in progress
});ProgressInfo
fn progress_info(&mut self, name: &str, value: &str)
This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.
Note: Some Chilkat methods don't fire any ProgressInfo events.
Example (closure form; the EventHandler trait method is equivalent):
rest.on_progress_info(|name, value| println!("{name}: {value}"));