NIM http client example| http GET, POST API tutorial?

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

Nim HTTP GET request example

Synchronous GET Request example:

  • First, Import the std/httpclient module
  • create an object of HttpClient i.e client variable
  • call getContent() method on variable
  • print to console
import 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

  • Create a procedure that returns String content of the Future type. added the procedure with async type
  • Inside a procedure, Create a variable for the newAsyncHttpClient type
  • call getContent and return it.
  • Finally, Call procedure in the event loop using waitFor

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()

Nim Http Client POST Request API with example

This section explains how to make an HTTP POST Request API in Nim WIth an example

  • Create a HttpClient object
  • Create a Headers using the HttpHeaders type
  • Create a body object
  • pass API URL, HttpPost, and body to the client request method
  • Print the status and body of a response.
import 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
}