C Program to Call a REST API Using libcurl

Modern applications often need to communicate with web services. APIs are widely used to fetch data such as weather information, cryptocurrency prices, and database records.

In this tutorial, you will learn how to create a simple REST API client in C using the libcurl library. This approach is commonly used in embedded systems, backend services, and network tools.

Concept Overview

libcurl is a powerful C library used for transferring data using multiple protocols such as HTTP, HTTPS, FTP, and more.

  • Send HTTP requests
  • Receive server responses
  • Integrate external APIs
  • Build network-enabled C applications

Program

C
#include <stdio.h>
#include <curl/curl.h>

int main(void) {
    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();

    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://api.github.com");
        curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");

        res = curl_easy_perform(curl);

        if(res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));

        curl_easy_cleanup(curl);
    }

    return 0;
}

Output

The program sends a request to the GitHub API and prints the response data returned by the server.

Explanation

  • `#include ` – Includes the libcurl library required for HTTP communication.
  • `curl_easy_init()` – Initializes the libcurl session.
  • `curl_easy_setopt()` – Sets request options such as the API URL.
  • `curl_easy_perform()` – Executes the HTTP request.
  • `curl_easy_cleanup()` – Frees resources used by libcurl.

Real World Applications

  • Connecting IoT devices to cloud APIs
  • Fetching live data from web services
  • Building command line API tools
  • Network monitoring systems