Write C Program to Check Weather Through API

 Welcome back to our website govtjobsyllabus.in . In today's post, we are going to discuss How do I make a program in C that fetches the weather through the web?.

In this program, you need an API of any weather website which can help you to provide current weather data.

So now stop wasting time and let's start our code:

C Program to Check Weather Through API
C Program to Check Weather Through API

C program for weather forecast

#include <stdio.h> #include <stdlib.h> #include <curl/curl.h> #include <json-c/json.h> // Function to write fetched data into a string size_t write_callback(void *contents, size_t size, size_t nmemb, char *output) { strcat(output, (char *)contents); return size * nmemb; } int main() { CURL *curl; CURLcode res; char url[100] = "http://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q="; char location[50]; char completeUrl[150]; char fetchedData[10000] = ""; printf("Enter the location: "); scanf("%s", location); strcat(url, location); strcpy(completeUrl, url); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, completeUrl); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fetchedData); res = curl_easy_perform(curl); curl_easy_cleanup(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); return 1; } // Parse the fetched data as JSON struct json_object *parsed_json; struct json_object *location_obj; struct json_object *current_obj; struct json_object *temp_c; struct json_object *condition; parsed_json = json_tokener_parse(fetchedData); json_object_object_get_ex(parsed_json, "location", &location_obj); json_object_object_get_ex(parsed_json, "current", &current_obj); json_object_object_get_ex(location_obj, "name", &location_obj); json_object_object_get_ex(current_obj, "temp_c", &temp_c); json_object_object_get_ex(current_obj, "condition", &condition); printf("\nLocation: %s\n", json_object_get_string(location_obj)); printf("Temperature: %s°C\n", json_object_get_string(temp_c)); printf("Condition: %s\n", json_object_get_string(condition)); } return 0; }

Explain Weather Forecast 

  • As you can see we include all basic library stdio.h, stdlib.h (memory allocation) but in this code we include two advanced libraries like curl/curl.h (making HTTP requests), json-c/json.h (parsing JSON data).

  • Now let's talk about 'write_callback' and this function is called by libcurl and stores the weather data which is fetched from the website.

  • Now start the 'main' function and curl is defined to handle the CURL and 'res' (use to store the result) and other arrays to manage the URL. 

  • CURL handle is initialized using curl_easy_init().

CURL FunctionDescription
curl_easy_initInitializes a CURL session and returns a CURL handle.
curl_easy_setoptSets options for the CURL request like URL and other.
curl_easy_performPerforms the CURL request synchronously. It initiates the request and blocks until the transfer is complete, retrieving the data from the specified URL.
curl_easy_strerrorConverts a CURLcode error to a human-readable string describing the error.
curl_easy_cleanupCleans up and frees resources.
curl_easy_escapeEscapes special characters in the URL and make sure it incodes properly.
json_tokener_parseParses a JSON-formatted string and returns a JSON object.
json_object_object_get_exRetrieves a JSON object from a parsed JSON data by its key and assigns it to the specified JSON object pointer.
json_object_get_stringRetrieves the string representation of a JSON object.

  • Finally, see the output.

Note:- install  libcurl and json-c libraries for this program for windows users you have to download the precompiled binaries from the official libcurl website (https://curl.se/windows/).


Here in this post, we add a mini project in c language so if you want to try your skill then you can read this post till the end.

No comments:

Post a Comment

Popular Posts