THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial explains multiple examples of HTTP client examples in NIm
HTTP requests are issued synchronously and asynchronously to make API calls.
HttpClient
is an object in the std/httpclient
module to make a synchronous request
Synchronous GET Request example:
std/httpclient
moduleHttpClient
i.e client
variablegetContent()
method on variableimport std/httpclient
var httpClient = newHttpClient()
echo httpClient.getContent("http://abc.com")
Asynchronous GET Request example:
newAsyncHttpClient
makes an asynchronous request. You have to use async
, and await
keywords to achieve asynchronous calls.
The asyncdispatch
module contains an asynchronous event loop to make async http client requests.
It contains the waitFor
procedure, that runs an event loop
Future
type. added the procedure with async typewaitFor
here is an example
import std/[asyncdispatch, httpclient]
proc asyncHttpGetRequest(): Future[string] {.async.} =
var httpClient = newAsyncHttpClient()
return await httpClient.getContent("http://abc.com")
echo waitFor asyncHttpGetRequest()
This section explains how to make an HTTP POST Request API in Nim WIth an example
HttpClient
objectHttpHeaders
typebody
objectHttpPost
, and body
to the client request
methodimport std/[httpclient, json]
try:
let client = newHttpClient()
client.headers = newHttpHeaders({ "Content-Type": "application/json" })
let body = %*{
"id": 2
}
let response = client.request("http://jsonplaceholder.typicode.com/posts", httpMethod = HttpPost, body = $body)
echo response.status
echo response.body
except:
echo "Error occurred";
Output
201 Created
{
"id": 101
}
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts