Search code examples
ccurllibcurl

How do I pass variable data into libcurl post body?


I'm having an issue passing the value of the variable into the POST Body while using libcurl. Here's my code :

#include "curl/curl.h"

char *fullname ="morpheus";
char *role = "leader";

CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(curl, CURLOPT_URL, "https://reqres.in/api/users");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers, "Content-Type: text/json");
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  const char *data = "{\"name\": \"${fullname}\" ,\"job\":\"${role}\"}";
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, function_pt);
  res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);

Solution

  • You are passing the name of the variable itself as a string. You have to concatenate the value, not the name.

    #include "curl/curl.h"
    
    char *fullname ="morpheus";
    char *role = "leader";
    
    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    if(curl) {
      curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
      curl_easy_setopt(curl, CURLOPT_URL, "https://reqres.in/api/users");
      curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
      curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
      struct curl_slist *headers = NULL;
      headers = curl_slist_append(headers, "Content-Type: text/json");
      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
      char *data = "{\"name\":";
      strcat(data, fullname);
      strcat(data, ",\"job\":\");
      strcat(data, role);;
      strcat(data, "\"}");
      curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, function_pt);
      res = curl_easy_perform(curl);
    }
    curl_easy_cleanup(curl);
    

    It is certainly not the cleanest way, but it will work out.