Skip to content

Instantly share code, notes, and snippets.

@manniresystems
Last active December 9, 2022 01:47
Show Gist options
  • Save manniresystems/2bd3ff1fbac52d6fb7f75ff87c38d4b8 to your computer and use it in GitHub Desktop.
Save manniresystems/2bd3ff1fbac52d6fb7f75ff87c38d4b8 to your computer and use it in GitHub Desktop.
write complete c program to connect to firestore?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <jansson.h>
// This function is called by libcurl when it receives a chunk of data from the server
size_t write_data(char *ptr, size_t size, size_t nmemb, void *userdata)
{
// Append the received data to the buffer
json_t *root = (json_t *)userdata;
json_error_t error;
json_t *data = json_loads(ptr, 0, &error);
json_array_extend(root, data);
// Return the number of bytes received to indicate success
return size * nmemb;
}
int main(int argc, char *argv[])
{
// Initialize the libcurl and jansson libraries
curl_global_init(CURL_GLOBAL_ALL);
json_set_alloc_funcs(malloc, free);
// Create a new CURL handle
CURL *curl = curl_easy_init();
if (curl)
{
// Set the URL to send the request to
curl_easy_setopt(curl, CURLOPT_URL, "https://firestore.googleapis.com/v1/projects/myproject/databases/(default)/documents/mycollection");
// Set the request method to GET
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
// Set the callback function to receive the response data
json_t *root = json_array();
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, root);
// Send the request and get the response
CURLcode res = curl_easy_perform(curl);
// Check for errors
if (res != CURLE_OK)
{
fprintf(stderr, "Error: %s\n", curl_easy_strerror(res));
}
else
{
// Parse the response data
json_t *documents = json_object_get(root, "documents");
if (json_is_array(documents))
{
// Print the names of the documents
printf("List of documents:\n");
size_t index;
json_t *document;
json_array_foreach(documents, index, document)
{
json_t *name = json_object_get(document, "name");
printf("%s\n", json_string_value(name));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment