• <GetStart>
  • CSPro User's Guide
    • The CSPro System
    • Data Dictionary Module
    • The CSPro Language
    • Data Entry Module
    • Batch Editing Applications
    • Tabulation Applications
    • Data Sources
    • Synchronization
    • CSPro Statements and Functions
    • Text Templates
    • Templated Reporting System
    • HTML, Markdown, and JavaScript Integration
    • Action Invoker
      • Overview
      • Execution Environments
      • Security, Resource Management, and Formatting Options
      • Base Actions
      • Application Namespace
      • Clipboard Namespace
      • Data Namespace
      • Dictionary Namespace
      • File Namespace
      • Hash Namespace
      • Localhost Namespace
      • Logic Namespace
      • Message Namespace
      • Network Namespace
        • Network Action Invoker Namespace
        • Network.fetch Action
        • Network.fetchBody Action
        • Network.fetchBytes Action
        • Network.fetchFile Action
        • Network.fetchJson Action
        • Network.fetchText Action
      • Path Namespace
      • Settings Namespace
      • Sqlite Namespace
      • Sync Namespace
      • System Namespace
      • UI Namespace
    • Appendix
  • <CSEntry>
  • <CSBatch>
  • <CSTab>
  • <DataManager>
  • <TextView>
  • <TblView>
  • <CSFreq>
  • <CSDeploy>
  • <CSPack>
  • <CSDiff>
  • <CSConcat>
  • <Excel2CSPro>
  • <CSExport>
  • <CSIndex>
  • <CSReFmt>
  • <CSSort>
  • <ParadataConcat>
  • <ParadataViewer>
  • <CSCode>
  • <CSDocument>
  • <CSView>
  • <CSWeb>

Network.fetch Action

Format
s = CS.Network.fetch(url := ...
                 
ʃ, method := ...ʅ
                 
ʃ, headers := ...ʅ
                 
ʃ, body := ...ʅʃ, bodyFormat := ...ʅ
                 
ʃ, responseHeadersFormat := ...ʅ)
ArgumentDescriptionTypes / Required
urlThe URL to fetch.string
required
methodThe HTTP request method.
The default value is is "GET".
string
not required
headersRequest headers to send to the server.array, object
not required
bodyThe body to include with the request.object, string
not required
bodyFormatThe format of the body.
The default value is "autodetect".
string
not required
responseHeadersFormatIndicates how response headers are returned.
The default value is "object".
string
not required
Description
The Network.fetch action submits a HTTP request to a server and returns details about the response. When the response results in a HTTP status code in the range 200 - 299, the action returns a resource ID, fetchId, that can be used to retrieve the response body using the action Network.fetchBody.
This action is useful as a way to initiate requests where the result may not fall in the "ok" range. For simpler requests, there are actions that serve as wrappers around this and Network.fetchBody. The convenience methods include:
  • Network.fetchBytes: The response is returned as binary data.
  • Network.fetchFile: The response is saved to the disk.
  • Network.fetchJson: The response is parsed as JSON and returned as an array, object, etc.
  • Network.fetchText: The response is returned as text.
URL
The required argument, url, specifies the address of the server resource to access, such as a file or an API endpoint. The URL must contain valid characters. To convert dynamic text to a valid URL, use the encode function with the arguments URI or URIComponent.
Method
The optional argument, method, details the HTTP request method, with the argument defaulting to "GET". The possible options include:
MethodOption
"GET""The GET method requests a representation of the specified resource."
"POST""The POST method submits an entity to the specified resource, often causing a change in state or side effects on the server." When using POST, you must specify a body.
"PUT""The PUT method replaces all current representations of the target resource with the request content."
"DELETE""The DELETE method deletes the specified resource."
Headers
You can include additional information in the request by specifying headers to send as part of the HTTP request. When specified as an array, or if an array element is a string, it is added as a fully defined header. If the headers are specified as an object, or if an array element is an object, that object's key/value pairs are combined to create a header with the object's key corresponding to a header name, and the object's value corresponding to a header value.
For example, the following headers, shown as a JSON array and object, are identical:
[
 
"Accept: application/json",
 
"Authorization: Bearer ACCESS_TOKEN"
]
{
 
"Accept": "application/json",
 
"Authorization": "Bearer ACCESS_TOKEN"
}
Body
If your request requires a payload, such as when using the POST method, the request body is specified using the argument body, with the format optionally specified using bodyFormat.
The body will be treated as JSON when:
  • bodyFormat is "json".
  • bodyFormat is undefined and:
    • body is defined as an object;
    • or the header has "Content-Type" set to "application/json".
For example, the body specified in these arguments would be treated as JSON:
{
 
"url": "https://...",
 
"body": {
   
"name": "CSPro Mailing List",
   
"email": "cspro@lists.census.gov"
  }
}
If none of these JSON-related conditions applies, the body is converted from binary data specified using a string. If the body's MIME type is known (e.g., from a data URL), a "Content-Type" header with this type will be set if no such header exists. For example:
{
 
"url": "https://...",
 
"method": "POST",
 
"body": "Hello, World!",
 
"bodyFormat": "text"
}
Return Value
The action returns an object containing information about the response:
KeyValue
"fetchId"A numeric resource ID that identifies this successful response's body. This can be used to retrieve the response body using the action Network.fetchBody.
"status"A number indicating the HTTP status code of the response.
"ok"A boolean flag indicating if the response was successful. Success is a status code in the range 200 - 299.
"headers"An object, or array, based on the optional argument responseHeadersFormat, with the response headers. If returned as an object, which is the default setting, the header names and values are represented as the keys and values of the "headers" object. If returned as an array, the headers are returned as an array of strings. The response header format mirrors that of the request headers detailed above.
"error"Text from the server, returned as the response body, describing the error if the response was received unsuccessfully.
Exceptions
The action throws an exception if any of its arguments are not specified in a valid form or if there is an error submitting the HTTP request. Unlike the other fetch convenience methods, an exception is not thrown if the response status code is not in the range 200 - 299.
Example 1 (JavaScript)
// query information about the latest CSPro commit;
// the GitHub API requires the specification of a User-Agent header
const response = CS.Network.fetch({
    url: 
"https://api.github.com/repos/csprousers/cspro/commits?per_page=1",
    headers: [
       
"User-Agent: CSPro Help Documentation Example"
    ]
});

if (response.ok) {
   
// with a successful response, retrieve the body as JSON using the
    // resource ID (fetchId) returned from the initial call to Network.fetch
    const commits = CS.Network.fetchBody({
        fetchId: response.fetchId,
        bodyFormat: 
"json"
    });

   
const latestCommit = commits[0].commit;

    console.log(`Latest commit authored by 
"${latestCommit.author.name}", ` +
                `committed on 
"${latestCommit.committer.date}", ` +
                `
with message: "${latestCommit.message"}"`);
}
Example 2 (JavaScript)
// request a page that returns a 404 Not Found response
const response = CS.Network.fetch({
    url: 
"https://httpbin.org/status/404",
    responseHeadersFormat: 
"array"
});

// displays: Response "status" = 404, "ok" = false, first "header" = HTTP/1.1 404 NOT FOUND
console.log(`Response "status" = ${response.status}, "ok" = ${response.ok}, first "header" = ${response.headers[0]}`);
See also: Network Action Invoker Namespace, Network.fetchBody Action