-2

How to make a HTTP request in Nim?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Alexandre Daubricourt
  • 3,323
  • 1
  • 34
  • 33

2 Answers2

2

This is answered in the first couple of lines of the httpclient documentation, along with POST, file POST, SSL, Proxy, timeouts and redirect handling...

Sync:

import std/httpclient

var client = newHttpClient()
echo client.getContent("http://google.com")

Async:

import std/[asyncdispatch, httpclient]

proc asyncProc(): Future[string] {.async.} =
  var client = newAsyncHttpClient()
  return await client.getContent("http://example.com")

echo waitFor asyncProc()
xbello
  • 7,223
  • 3
  • 28
  • 41
0

A sample for a POST request, using async.

import httpclient
import asyncdispatch

proc main(): Future[void] {.async.} =
  let client = newAsyncHttpClient()
  client.headers = newHttpHeaders({"Content-Type": "application/json"})
  let res = await client.request("https://stackoverflow.com/",
      httpMethod = HttpPost, body = "some data")
  let resBody = await res.body
  echo resBody
Alexandre Daubricourt
  • 3,323
  • 1
  • 34
  • 33