Source Edit

This module implements a simple HTTP client that can be used to retrieve webpages and other data.

Warning: Validate untrusted inputs: URI parsers and getters are not detecting malicious URIs.

Retrieving a website

This example uses HTTP GET to retrieve http://google.com:

  1. import std/httpclient
  2. var client = newHttpClient()
  3. try:
  4. echo client.getContent("http://google.com")
  5. finally:
  6. client.close()

The same action can also be performed asynchronously, simply use the AsyncHttpClient:

  1. import std/[asyncdispatch, httpclient]
  2. proc asyncProc(): Future[string] {.async.} =
  3. var client = newAsyncHttpClient()
  4. try:
  5. return await client.getContent("http://google.com")
  6. finally:
  7. client.close()
  8. echo waitFor asyncProc()

The functionality implemented by HttpClient and AsyncHttpClient is the same, so you can use whichever one suits you best in the examples shown here.

Note: You need to run asynchronous examples in an async proc otherwise you will get an Undeclared identifier: ‘await’ error.

Note: An asynchronous client instance can only deal with one request at a time. To send multiple requests in parallel, use multiple client instances.

Using HTTP POST

This example demonstrates the usage of the W3 HTML Validator, it uses multipart/form-data as the Content-Type to send the HTML to be validated to the server.

  1. var client = newHttpClient()
  2. var data = newMultipartData()
  3. data["output"] = "soap12"
  4. data["uploaded_file"] = ("test.html", "text/html",
  5. "<html><head></head><body><p>test</p></body></html>")
  6. try:
  7. echo client.postContent("http://validator.w3.org/check", multipart=data)
  8. finally:
  9. client.close()

To stream files from disk when performing the request, use addFiles.

Note: This will allocate a new Mimetypes database every time you call it, you can pass your own via the mimeDb parameter to avoid this.

  1. let mimes = newMimetypes()
  2. var client = newHttpClient()
  3. var data = newMultipartData()
  4. data.addFiles({"uploaded_file": "test.html"}, mimeDb = mimes)
  5. try:
  6. echo client.postContent("http://validator.w3.org/check", multipart=data)
  7. finally:
  8. client.close()

You can also make post requests with custom headers. This example sets Content-Type to application/json and uses a json object for the body

  1. import std/[httpclient, json]
  2. let client = newHttpClient()
  3. client.headers = newHttpHeaders({ "Content-Type": "application/json" })
  4. let body = %*{
  5. "data": "some text"
  6. }
  7. try:
  8. let response = client.request("http://some.api", httpMethod = HttpPost, body = $body)
  9. echo response.status
  10. finally:
  11. client.close()

Progress reporting

You may specify a callback procedure to be called during an HTTP request. This callback will be executed every second with information about the progress of the HTTP request.

  1. import std/[asyncdispatch, httpclient]
  2. proc onProgressChanged(total, progress, speed: BiggestInt) {.async.} =
  3. echo("Downloaded ", progress, " of ", total)
  4. echo("Current rate: ", speed div 1000, "kb/s")
  5. proc asyncProc() {.async.} =
  6. var client = newAsyncHttpClient()
  7. client.onProgressChanged = onProgressChanged
  8. try:
  9. discard await client.getContent("http://speedtest-ams2.digitalocean.com/100mb.test")
  10. finally:
  11. client.close()
  12. waitFor asyncProc()

If you would like to remove the callback simply set it to nil.

  1. client.onProgressChanged = nil

Warning: The total reported by httpclient may be 0 in some cases.

SSL/TLS support

This requires the OpenSSL library. Fortunately it’s widely used and installed on many operating systems. httpclient will use SSL automatically if you give any of the functions a url with the https schema, for example: https://github.com/.

You will also have to compile with ssl defined like so: nim c -d:ssl ….

Certificate validation is performed by default.

A set of directories and files from the ssl_certs module are scanned to locate CA certificates.

Example of setting SSL verification parameters in a new client:

  1. import httpclient
  2. var client = newHttpClient(sslContext=newContext(verifyMode=CVerifyPeer))

There are three options for verify mode:

  • CVerifyNone: certificates are not verified;
  • CVerifyPeer: certificates are verified;
  • CVerifyPeerUseEnvVars: certificates are verified and the optional environment variables SSL_CERT_FILE and SSL_CERT_DIR are also used to locate certificates

See newContext to tweak or disable certificate validation.

Timeouts

Currently only the synchronous functions support a timeout. The timeout is measured in milliseconds, once it is set any call on a socket which may block will be susceptible to this timeout.

It may be surprising but the function as a whole can take longer than the specified timeout, only individual internal calls on the socket are affected. In practice this means that as long as the server is sending data an exception will not be raised, if however data does not reach the client within the specified timeout a TimeoutError exception will be raised.

Here is how to set a timeout when creating an HttpClient instance:

  1. import std/httpclient
  2. let client = newHttpClient(timeout = 42)

Proxy

A proxy can be specified as a param to any of the procedures defined in this module. To do this, use the newProxy constructor. Unfortunately, only basic authentication is supported at the moment.

Some examples on how to configure a Proxy for HttpClient:

  1. import std/httpclient
  2. let myProxy = newProxy("http://myproxy.network")
  3. let client = newHttpClient(proxy = myProxy)

Use proxies with basic authentication:

  1. import std/httpclient
  2. let myProxy = newProxy("http://myproxy.network", auth="user:password")
  3. let client = newHttpClient(proxy = myProxy)

Get Proxy URL from environment variables:

  1. import std/httpclient
  2. var url = ""
  3. try:
  4. if existsEnv("http_proxy"):
  5. url = getEnv("http_proxy")
  6. elif existsEnv("https_proxy"):
  7. url = getEnv("https_proxy")
  8. except ValueError:
  9. echo "Unable to parse proxy from environment variables."
  10. let myProxy = newProxy(url = url)
  11. let client = newHttpClient(proxy = myProxy)

Redirects

The maximum redirects can be set with the maxRedirects of int type, it specifies the maximum amount of redirects to follow, it defaults to 5, you can set it to 0 to disable redirects.

Here you can see an example about how to set the maxRedirects of HttpClient:

  1. import std/httpclient
  2. let client = newHttpClient(maxRedirects = 0)

Imports

since, net, strutils, uri, parseutils, base64, os, mimetypes, math, random, httpcore, times, tables, streams, monotimes, asyncnet, asyncdispatch, asyncfile, nativesockets

Types

  1. AsyncHttpClient = HttpClientBase[AsyncSocket]

Source Edit

  1. AsyncResponse = ref object
  2. version*: string
  3. status*: string
  4. headers*: HttpHeaders
  5. bodyStream*: FutureStream[string]

Source Edit

  1. HttpClient = HttpClientBase[Socket]

Source Edit

  1. HttpClientBase[SocketType] = ref object
  2. ## Where we are currently connected.
  3. headers*: HttpHeaders ## Headers to send in requests.
  4. ## Maximum redirects, set to `0` to disable.
  5. timeout*: int ## Only used for blocking HttpClient for now.
  6. ## `nil` or the callback to call when request progress changes.
  7. when SocketType is Socket:
  8. onProgressChanged*: ProgressChangedProc[void]
  9. else:
  10. onProgressChanged*: ProgressChangedProc[Future[void]]
  11. when defined(ssl):
  12. when SocketType is AsyncSocket:
  13. else:
  14. ## When `false`, the body is never read in requestAux.

Source Edit

  1. HttpRequestError = object of IOError

Thrown in the getContent proc and postContent proc, when the server returns an error Source Edit

  1. MultipartData = ref object

Source Edit

  1. MultipartEntries = openArray[tuple[name, content: string]]

Source Edit

  1. ProgressChangedProc[ReturnType] = proc (total, progress, speed: BiggestInt): ReturnType {.
  2. closure, ...gcsafe.}

Source Edit

  1. ProtocolError = object of IOError

exception that is raised when server does not conform to the implemented protocol Source Edit

  1. Proxy = ref object
  2. url*: Uri
  3. auth*: string

Source Edit

  1. Response = ref object
  2. version*: string
  3. status*: string
  4. headers*: HttpHeaders
  5. bodyStream*: Stream

Source Edit

Consts

  1. defUserAgent = "Nim httpclient/2.0.8"

Source Edit

Procs

  1. proc `$`(data: MultipartData): string {....raises: [], tags: [], forbids: [].}

convert MultipartData to string so it’s human readable when echo see https://github.com/nim-lang/Nim/issues/11863 Source Edit

  1. proc `[]=`(p: MultipartData; name, content: string) {.inline,
  2. ...raises: [ValueError], tags: [], forbids: [].}

Add a multipart entry to the multipart data p. The value is added without a filename and without a content type.

  1. data["username"] = "NimUser"

Source Edit

  1. proc `[]=`(p: MultipartData; name: string;
  2. file: tuple[name, contentType, content: string]) {.inline,
  3. ...raises: [ValueError], tags: [], forbids: [].}

Add a file to the multipart data p, specifying filename, contentType and content manually.

  1. data["uploaded_file"] = ("test.html", "text/html",
  2. "<html><head></head><body><p>test</p></body></html>")

Source Edit

  1. proc add(p: MultipartData; name, content: string; filename: string = "";
  2. contentType: string = ""; useStream = true) {....raises: [ValueError],
  3. tags: [], forbids: [].}

Add a value to the multipart data.

When useStream is false, the file will be read into memory.

Raises a ValueError exception if name, filename or contentType contain newline characters.

Source Edit

  1. proc add(p: MultipartData; xs: MultipartEntries): MultipartData {.discardable,
  2. ...raises: [ValueError], tags: [], forbids: [].}

Add a list of multipart entries to the multipart data p. All values are added without a filename and without a content type.

  1. data.add({"action": "login", "format": "json"})

Source Edit

  1. proc addFiles(p: MultipartData; xs: openArray[tuple[name, file: string]];
  2. mimeDb = newMimetypes(); useStream = true): MultipartData {.
  3. discardable, ...raises: [IOError, ValueError], tags: [ReadIOEffect],
  4. forbids: [].}

Add files to a multipart data object. The files will be streamed from disk when the request is being made. When stream is false, the files are instead read into memory, but beware this is very memory ineffecient even for small files. The MIME types will automatically be determined. Raises an IOError if the file cannot be opened or reading fails. To manually specify file content, filename and MIME type, use []= instead.

  1. data.addFiles({"uploaded_file": "public/test.html"})

Source Edit

  1. proc body(response: AsyncResponse): Future[string] {....stackTrace: false,
  2. raises: [Exception, ValueError], tags: [RootEffect], forbids: [].}

Reads the response’s body and caches it. The read is performed only once. Source Edit

  1. proc body(response: Response): string {....raises: [IOError, OSError],
  2. tags: [ReadIOEffect], forbids: [].}

Retrieves the specified response’s body.

The response’s body stream is read synchronously.

Source Edit

  1. proc close(client: HttpClient | AsyncHttpClient)

Closes any connections held by the HTTP client. Source Edit

  1. proc code(response: Response | AsyncResponse): HttpCode {.
  2. ...raises: [ValueError, OverflowDefect].}

Retrieves the specified response’s HttpCode.

Raises a ValueError if the response’s status does not have a corresponding HttpCode.

Source Edit

  1. proc contentLength(response: Response | AsyncResponse): int

Retrieves the specified response’s content length.

This is effectively the value of the “Content-Length” header.

A ValueError exception will be raised if the value is not an integer. If the Content-Length header is not set in the response, ContentLength is set to the value -1.

Source Edit

  1. proc contentType(response: Response | AsyncResponse): string {.inline.}

Retrieves the specified response’s content type.

This is effectively the value of the “Content-Type” header.

Source Edit

  1. proc delete(client: AsyncHttpClient; url: Uri | string): Future[AsyncResponse] {.
  2. ...stackTrace: false.}

Connects to the hostname specified by the URL and performs a DELETE request. This procedure uses httpClient values such as client.maxRedirects. Source Edit

  1. proc delete(client: HttpClient; url: Uri | string): Response

Source Edit

  1. proc deleteContent(client: AsyncHttpClient; url: Uri | string): Future[string] {.
  2. ...stackTrace: false.}

Connects to the hostname specified by the URL and returns the content of a DELETE request. Source Edit

  1. proc deleteContent(client: HttpClient; url: Uri | string): string

Source Edit

  1. proc downloadFile(client: AsyncHttpClient; url: Uri | string; filename: string): Future[
  2. void]

Source Edit

  1. proc downloadFile(client: HttpClient; url: Uri | string; filename: string)

Downloads url and saves it to filename. Source Edit

  1. proc get(client: AsyncHttpClient; url: Uri | string): Future[AsyncResponse] {.
  2. ...stackTrace: false.}

Connects to the hostname specified by the URL and performs a GET request.

This procedure uses httpClient values such as client.maxRedirects.

Source Edit

  1. proc get(client: HttpClient; url: Uri | string): Response

Source Edit

  1. proc getContent(client: AsyncHttpClient; url: Uri | string): Future[string] {.
  2. ...stackTrace: false.}

Connects to the hostname specified by the URL and returns the content of a GET request. Source Edit

  1. proc getContent(client: HttpClient; url: Uri | string): string

Source Edit

  1. proc getSocket(client: AsyncHttpClient): AsyncSocket {.inline, ...raises: [],
  2. tags: [], forbids: [].}

Source Edit

  1. proc getSocket(client: HttpClient): Socket {.inline, ...raises: [], tags: [],
  2. forbids: [].}

Get network socket, useful if you want to find out more details about the connection

this example shows info about local and remote endpoints

  1. if client.connected:
  2. echo client.getSocket.getLocalAddr
  3. echo client.getSocket.getPeerAddr

Source Edit

  1. proc head(client: AsyncHttpClient; url: Uri | string): Future[AsyncResponse] {.
  2. ...stackTrace: false.}

Connects to the hostname specified by the URL and performs a HEAD request.

This procedure uses httpClient values such as client.maxRedirects.

Source Edit

  1. proc head(client: HttpClient; url: Uri | string): Response

Source Edit

  1. proc lastModified(response: Response | AsyncResponse): DateTime

Retrieves the specified response’s last modified time.

This is effectively the value of the “Last-Modified” header.

Raises a ValueError if the parsing fails or the value is not a correctly formatted time.

Source Edit

  1. proc newAsyncHttpClient(userAgent = defUserAgent; maxRedirects = 5;
  2. sslContext = getDefaultSSL(); proxy: Proxy = nil;
  3. headers = newHttpHeaders()): AsyncHttpClient {.
  4. ...raises: [], tags: [], forbids: [].}

Creates a new AsyncHttpClient instance.

userAgent specifies the user agent that will be used when making requests.

maxRedirects specifies the maximum amount of redirects to follow, default is 5.

sslContext specifies the SSL context to use for HTTPS requests.

proxy specifies an HTTP proxy to use for this HTTP client’s connections.

headers specifies the HTTP Headers.

Example:

  1. import std/[asyncdispatch, strutils]
  2. proc asyncProc(): Future[string] {.async.} =
  3. let client = newAsyncHttpClient()
  4. result = await client.getContent("http://example.com")
  5. let exampleHtml = waitFor asyncProc()
  6. assert "Example Domain" in exampleHtml
  7. assert "Pizza" notin exampleHtml

Source Edit

  1. proc newHttpClient(userAgent = defUserAgent; maxRedirects = 5;
  2. sslContext = getDefaultSSL(); proxy: Proxy = nil;
  3. timeout = -1; headers = newHttpHeaders()): HttpClient {.
  4. ...raises: [], tags: [], forbids: [].}

Creates a new HttpClient instance.

userAgent specifies the user agent that will be used when making requests.

maxRedirects specifies the maximum amount of redirects to follow, default is 5.

sslContext specifies the SSL context to use for HTTPS requests. See SSL/TLS support

proxy specifies an HTTP proxy to use for this HTTP client’s connections.

timeout specifies the number of milliseconds to allow before a TimeoutError is raised.

headers specifies the HTTP Headers.

Example:

  1. import std/strutils
  2. let exampleHtml = newHttpClient().getContent("http://example.com")
  3. assert "Example Domain" in exampleHtml
  4. assert "Pizza" notin exampleHtml

Source Edit

  1. proc newMultipartData(): MultipartData {.inline, ...raises: [], tags: [],
  2. forbids: [].}

Constructs a new MultipartData object. Source Edit

  1. proc newMultipartData(xs: MultipartEntries): MultipartData {.
  2. ...raises: [ValueError], tags: [], forbids: [].}

Create a new multipart data object and fill it with the entries xs directly.

  1. var data = newMultipartData({"action": "login", "format": "json"})

Source Edit

  1. proc newProxy(url: string; auth = ""): Proxy {....raises: [], tags: [], forbids: [].}

Constructs a new TProxy object. Source Edit

  1. proc newProxy(url: Uri; auth = ""): Proxy {....raises: [], tags: [], forbids: [].}

Constructs a new TProxy object. Source Edit

  1. proc patch(client: AsyncHttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): Future[AsyncResponse] {.
  3. ...stackTrace: false.}

Connects to the hostname specified by the URL and performs a PATCH request. This procedure uses httpClient values such as client.maxRedirects. Source Edit

  1. proc patch(client: HttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): Response

Source Edit

  1. proc patchContent(client: AsyncHttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): Future[string] {.
  3. ...stackTrace: false.}

Connects to the hostname specified by the URL and returns the content of a PATCH request. Source Edit

  1. proc patchContent(client: HttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): string

Source Edit

  1. proc post(client: AsyncHttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): Future[AsyncResponse] {.
  3. ...stackTrace: false.}

Connects to the hostname specified by the URL and performs a POST request. This procedure uses httpClient values such as client.maxRedirects. Source Edit

  1. proc post(client: HttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): Response

Source Edit

  1. proc postContent(client: AsyncHttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): Future[string] {.
  3. ...stackTrace: false.}

Connects to the hostname specified by the URL and returns the content of a POST request. Source Edit

  1. proc postContent(client: HttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): string

Source Edit

  1. proc put(client: AsyncHttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): Future[AsyncResponse] {.
  3. ...stackTrace: false.}

Connects to the hostname specified by the URL and performs a PUT request. This procedure uses httpClient values such as client.maxRedirects. Source Edit

  1. proc put(client: HttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): Response

Source Edit

  1. proc putContent(client: AsyncHttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): Future[string] {.
  3. ...stackTrace: false.}

Connects to the hostname specified by the URL andreturns the content of a PUT request. Source Edit

  1. proc putContent(client: HttpClient; url: Uri | string; body = "";
  2. multipart: MultipartData = nil): string

Source Edit

  1. proc request(client: AsyncHttpClient; url: Uri | string;
  2. httpMethod: HttpMethod | string = HttpGet; body = "";
  3. headers: HttpHeaders = nil; multipart: MultipartData = nil): Future[
  4. AsyncResponse] {....stackTrace: false.}

Connects to the hostname specified by the URL and performs a request using the custom method string specified by httpMethod.

Connection will be kept alive. Further requests on the same client to the same hostname will not require a new connection to be made. The connection can be closed by using the close procedure.

This procedure will follow redirects up to a maximum number of redirects specified in client.maxRedirects.

You need to make sure that the url doesn’t contain any newline characters. Failing to do so will raise AssertionDefect.

headers are HTTP headers that override the client.headers for this specific request only and will not be persisted.

Deprecated since v1.5: use HttpMethod enum instead; string parameter httpMethod is deprecated

Source Edit

  1. proc request(client: HttpClient; url: Uri | string;
  2. httpMethod: HttpMethod | string = HttpGet; body = "";
  3. headers: HttpHeaders = nil; multipart: MultipartData = nil): Response

Source Edit

Exports

Http417, Http503, Http431, HttpTrace, contains, Http304, Http406, $, HttpMethod, Http408, is4xx, is1xx, Http411, is3xx, Http207, Http418, Http206, HttpHead, HttpPost, clear, Http101, httpNewLine, Http505, Http413, Http423, Http409, hasKey, Http200, []=, Http414, add, Http401, Http511, Http205, \==, Http407, Http500, Http404, Http416, Http507, Http302, HttpHeaders, Http300, Http428, Http410, is2xx, Http202, Http502, headerLimit, HttpHeaderValues, Http425, contains, newHttpHeaders, $, [], Http510, newHttpHeaders, Http305, Http451, Http504, Http426, HttpConnect, \==, Http308, del, HttpPut, Http402, pairs, Http429, HttpVersion, HttpDelete, is5xx, Http421, HttpOptions, Http307, Http102, Http301, HttpPatch, Http201, Http203, getOrDefault, Http100, Http208, Http501, []=, len, Http506, Http400, Http403, HttpGet, Http508, Http415, toString, Http412, Http103, Http405, Http303, Http204, Http424, HttpCode, Http422, Http226, []