afHttpClientExt icon

afHttpClientExt

Axon functions for making HTTP requests to REST APIs
afHttpClientExtAxon funcs

Registered StackHub users may elect to receive email notifications whenever a new package version is released or a comment is posted on the forum.

There are 13 watchers.

v2.1.16

afHttpAuth
afHttpAuth(authScheme, username, password: null)

Forces authentication to be performed as part of the next HTTP request. Valid built in authentication schemes are:

  • basic
  • bearer (leave password as null)
  • digest
  • haystack
  • header
  • path
  • query
  • cert

If password is a Ref, then it is used to lookup the real password from SkySpark's secure password store.

All credentials set via afHttpAuth() are masked / starred out from debug logs, so using the SkySpark secure store means your passwords are never revealed!

Credentials need only be set once per session, and are re-used in all subsequent requests to the same domain.

Example:

passwordSet(@xxxx-xxxx, "<password>")
afHttpAuth("basic", "username", @xxxx-xxxx)
afHttpGet(`http://example1.com/secret.txt`)

afHttpAuth("bearer", @yyyy-yyyy)
afHttpGet(`http://example2.com/some-other-secret.txt`)

Need a secure custom or OAuth2 authentication scheme for HTTP Client? Ask Fantom Factory to write it for you?

While basic, bearer, digest, and haystack are Internet standards, header, path, and query are custom schemes that address common authentication scenarios.

header sets a custom HTTP request header value.

afHttpAuth("header", "X-Auth", "xxxx-xxxx")
afHttpGet(`http://example.com/api/endPoint`)

GET /api/endPoint HTTP/1.1
Host: example.com
X-Auth: xxxx-xxxx

path replaces a named URL path segment with the given value.

afHttpAuth("path", "<api-key>", "xxxx-xxxx")
afHttpGet(`http://example.com/api/<api-key>/endPoint`)

GET /api/xxxx-xxxx/endPoint HTTP/1.1
Host: example.com

query sets a URL query parameter with the given value.

afHttpAuth("query", "api-key", "xxxx-xxxx")
afHttpGet(`http://example.com/api/endPoint`)

GET /api/endPoint?api-key=xxxx-xxxx HTTP/1.1
Host: example.com

cert sets the SocketConfig with the keystore from the specified certificate loaded.

When using the cert auth scheme, username MUST be a Uri that points to the certificate file. Certificate file handles are resolved in the same format as ioHandle. The password argument is the passphrase used to unlock the certificate, if left as null, both null and an empty string "" are attempted to unlock the certificate.

No masking of the headers is added for cert auth.

afHttpAuth("query", `io/certs/certificate.p12`, "xxxx-xxxx")
afHttpGet(`http://example.com/api/endPoint`)

While these authentication mechanisms may seem simple, they offer a very secure means of supplying passwords to APIs when used in conjunction with SkySpark's secure store (by passing a Ref as the password) and by masking credentials from debug messages.

Fantom signature:
@Axon static Void afHttpAuth(Str authScheme, Obj username, Obj? password := null)
afHttpClear
afHttpClear(opts: null)

Resets the HTTP Ext back to an original (pre-session) state.

Calling with no arguments will reset everything.

afHttpClear()

To just clear the session (cookies and authentication credentials), pass a session flag:

afHttpClear({session})

To clear the default behaviour for a HTTP response status code, pass in the exact code, or a glob string for wildcards:

// do not error on "404 - Not Found" status codes
afHttpClear({statusCode:404})

// do not follow redirects
afHttpClear({statusCode:"3xx"})

Other configuration may be removed / cleared.

// remove content compression
afHttpClear({contentDecode:"gzip"})
afHttpClear({contentDecode:"deflate"})

// remove 'connectTimeout' and 'receiveTimeout' socket config
afHttpClear({socketOptions})
Fantom signature:
@Axon static Void afHttpClear(Dict? opts := null)
afHttpConfig
afHttpConfig(config)

Sets config for the current HTTP Client session.

// suppress the defalate header and adler checksum in responses
afHttpConfig({resDeflateNowrap:true})

// set advanced socket options
afHttpConfig({connectTimeout:30s, receiveTimeout:30s})
Fantom signature:
@Axon static Void afHttpConfig(Dict config)
afHttpCookies
afHttpCookies()

Returns a Grid of HTTP cookies stored in the current HTTP session. Use afHttpClear to clear them.

Fantom signature:
@Axon static Grid afHttpCookies()
afHttpDebug
afHttpDebug(on: true)

Turns debugging on / off. When on, all HTTP request / response data will be logged to the extension and printed to the console. This can greatly help in debugging unexpected responses from a server.

Passwords and credentials set via afHttpAuth() will be masked out, keeping them safe.

An example request, as logged to the console, would look like this.

HTTP Request to: https://example.com
GET /api/********/someEndPoint?q=******** HTTP/1.1
Host: example.com
Content-Length: 0
Authorization: ********
X-Auth: ********
Accept-Encoding: gzip;q=0.5, deflate;q=0.4
User-Agent: afHttpClient/2.1.6 (Fantom/1.0.77.3103 win32-x86_64)

For security reasons, because requests may hold other sensitive data, this function is for super users only.

Fantom signature:
@Axon { su=true; } static Void afHttpDebug(Bool on := true)
afHttpGet
afHttpGet(url, headers: null, body: null)

Makes a HTTP GET request to the given URL and returns the response body as a string. Note that body's aren't usually sent in GET requests.

Parameters:

  • url (Uri) - the URL (required)
  • headers (Dict) - HTTP request headers (optional)
  • body (Obj) - the request body (optional)

The body may be any object (Str, Grid, Dict, Uri, Fn) as described in Body Sniffing.

Examples:

afHttpGet(`http://example.com`)
afHttpGet(`http://example.com`, { "Content-Type" : "text/plain" }, "Hello Mum!")
Fantom signature:
@Axon static Str afHttpGet(Uri url, Dict? headers := null, Obj? body := null)
afHttpPost
afHttpPost(url, headers: null, body: null)

Makes a HTTP POST request to the given URL and returns the response body as a string.

Parameters:

  • url (Uri) - the URL (required)
  • headers (Dict) - HTTP request headers (optional)
  • body (Obj) - the request body (optional)

The body may be any object (Str, Grid, Dict, Uri, Fn) as described in Body Sniffing.

Examples:

afHttpPost(`http://example.com`)
afHttpPost(`http://example.com`, { "Content-Type" : "text/plain" }, "Hello Mum!")
Fantom signature:
@Axon static Str afHttpPost(Uri url, Dict? headers := null, Obj? body := null)
afHttpReadFromJson
afHttpReadFromJson(jsonObj, opts: null)

Reads the given JSON string into Axon objects.

The Dict is converted using standard JSON notation and NOT Haystack JSON notation. Therefore afHttpReadFromJson() replaces the core ioReadJson() function when communicating with non-Haystack REST APIs.

Pass safeNames or camelCase as an option marker to convert JSON object names into SkySpark Grid-safe tag names. See Displaying Axon Dicts with non-standard keys for details.

(If in doubt, favour camelCase over safeNames as it normalises string values to common haystack usage.)

This function supports reading the following types:

  • Dict
  • List
  • null
  • Bool
  • Number (without units)
  • Str

Example:

afHttpReadFromJson("""{"Name":"Emma", "Score":11}""", {camelCase})
Fantom signature:
@Axon static Obj? afHttpReadFromJson(Str? jsonObj, Dict? opts := null)
afHttpRequest
afHttpRequest(method, url, headers: null, body: null)

Makes a HTTP request to the given URL and method and returns the response body as a string.

Parameters:

  • method (Str) - the HTTP method (required)
  • url (Uri) - the URL (required)
  • headers (Dict) - HTTP request headers (optional)
  • body (Obj) - the request body (optional)

The body may be any object (Str, Grid, Dict, Uri, Fn) as described in Body Sniffing.

Examples:

afHttpRequest("GET", `http://example.com`)
afHttpRequest("PUT", `http://example.com`, { "Content-Type" : "text/plain" }, "Hello Mum!")
Fantom signature:
@Axon static Str afHttpRequest(Str method, Uri url, Dict? headers := null, Obj? body := null)
afHttpResponse
afHttpResponse(opts: null)

Returns a Dict of the last HTTP response.

Example response:

{
   "url"        : `http://example.com`,      // Uri
   "statusCode" : 200,                       // Number
   "statusMsg"  : "OK",                      // Str
   "headers"    : {"Content-Length" : 320},  // Dict
   "version"    : "1.1",                     // Str
   "body"       : "<html><head><title>..."   // Str
}

Note that displaying the HTTP response headers in a Grid may cause an Invalid col name error as per the SkySpark forum post: Displaying Axon Dicts with non-standard keys

To avoid this, pass camelCase or safeNames in as a option and the key names will be converted to SkySpark Grid safe tag names.

Example safe headers:

afHttpResponse({camelCase})->headers  // --> {"contentLength"  : 320}
afHttpResponse({safeNames})->headers  // --> {"content_Length" : 320}

(If in doubt, favour camelCase over safeNames as it normalises string values to much nicer common usage.)

afHttpResponse needs to be run in a function, and will return null if run directly in the Tools app.

Fantom signature:
@Axon static Dict? afHttpResponse(Dict? opts := null)
afHttpUriPlusQuery
afHttpUriPlusQuery(uri, query)

Add the specified query (key/value pairs) to the Uri. If the Uri has an existing query, then it is merged with the given query.

The key/value pairs should not be backslash escaped or percent encoded (this is done for you). If the query param is null or empty, then Uri is returned.

Examples:

`http://h/`      .afHttpUriPlusQuery({k:"v"})    // --> `http://h/?k=v`
`http://h/?k=old`.afHttpUriPlusQuery({k:"v"})    // --> `http://h/?k=v`
`/foo?a=b`       .afHttpUriPlusQuery({k:"v"})    // --> `/foo?a=b&k=v`
`/foo`           .afHttpUriPlusQuery({bar})      // --> `/foo?bar`
Fantom signature:
@Axon static Uri afHttpUriPlusQuery(Uri uri, Dict? query)
afHttpWriteToJson
afHttpWriteToJson(jsonObj, opts: null)

Writes the given Axon object to a JSON string.

The Dict is converted using standard JSON notation and NOT Haystack JSON notation. Therefore afHttpWriteToJson() replaces the core ioWriteJson() function when communicating with non-Haystack REST APIs.

This function only supports writing the following types:

  • Dict
  • List
  • null
  • Bool
  • Number (without units)
  • Str

Attempting to write an unsupported type results in an error.

Supported options are:

  • prettyPrint - Marker - Turns on pretty printing. (defaults to off)
  • indent - String - the string to use for indenting. (defaults to 2 spaces)
  • maxWidth - Number - Sets a max width for pretty printed strings. (defaults to 80)
  • lenient - Marker - ignores units in numbers, and unknown types are converted via toStr() and written as strings.

Note that Lists and Dict will only be pretty printed if they exceed maxWidth.

Example:

afHttpWriteToJson({name:"Emma", score:11}, {prettyPrint, indent:"  ", maxWidth:20})
Fantom signature:
@Axon static Str afHttpWriteToJson(Obj? jsonObj, Dict? opts := null)
Published by Fantom Factory

Products & Services by Fantom Factory

Packages by Fantom Factory

Commercial packages

Free packages