How to make a HTTP request in Nim?
Asked
Active
Viewed 583 times
2 Answers
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
-
That's not the way. This code doesn't compile, as `await` MUST be in an async proc. – xbello Jan 12 '23 at 16:18
-
Right! I did not intented to give a compilable program but rather a sample of the right modules and their usage. I see this can be misleading, just corrected. – Alexandre Daubricourt Jan 12 '23 at 19:52