MDStressLab++
Loading...
Searching...
No Matches
kim_query.cpp
Go to the documentation of this file.
1
2#include <iostream>
3#include <string>
4#include <initializer_list>
5#include <curl/curl.h>
6
7// A callback that writes data into a std::string
8static size_t write_callback(void* contents, size_t size, size_t nmemb, void* userp)
9{
10 const size_t totalSize = size * nmemb;
11 std::string& buffer = *static_cast<std::string*>(userp);
12 buffer.append(static_cast<char*>(contents), totalSize);
13 return totalSize;
14}
15
22std::string kim_query(
23 const std::string& query_function,
24 const std::initializer_list<std::string>& extra_args ={
25 "species=[]",
26 }
27)
28{
29 // URL to contact
30 const std::string url = "https://query.openkim.org/api/" + query_function;
31
32 // Build the POST fields
33 std::string post_data;
34
35 // Append extra_args, each one is "key=[stuff]"
36 for (auto& kv : extra_args) {
37 // If there's already something in post_data, prepend '&'
38 if (!post_data.empty()) {
39 post_data += "&";
40 }
41 post_data += kv;
42 }
43
44 // Initialize response string
45 std::string response;
46
47 // Initialize libcurl
48 curl_global_init(CURL_GLOBAL_DEFAULT);
49 CURL* curl_handle = curl_easy_init();
50 if (!curl_handle) {
51 curl_global_cleanup();
52 return "Error: Failed to initialize libcurl!";
53 }
54
55 curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYHOST, 0);
56 curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
57
58 // Set the options
59 curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());
60 curl_easy_setopt(curl_handle, CURLOPT_POST, 1L);
61 curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, post_data.c_str());
62 curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_callback);
63 curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, &response);
64
65 // Perform the request
66 CURLcode res = curl_easy_perform(curl_handle);
67 if (res != CURLE_OK) {
68 response = std::string("curl error: ") + curl_easy_strerror(res);
69 }
70
71 // Cleanup
72 curl_easy_cleanup(curl_handle);
73 curl_global_cleanup();
74
75 return response;
76}
77
78/*
79int main()
80{
81
82 std::string result2 = kim_query(
83 "get_available_models",
84 {
85 "species=[\"Si\",\"C\"]",
86 "species_logic=[\"and\"]",
87 "model_interface=[\"sm\"]",
88 "potential_type=[\"meam\"]",
89 "simulator_name=[\"LAMMPS\"]"
90 }
91 );
92 std::cout << "\nResponse from custom query:\n" << result2 << std::endl;
93 std::string result = kim_query(
94 "get_lattice_constant_cubic",
95 {
96 "model=[\"MO_123629422045_005\"]",
97 "crystal=[\"fcc\"]",
98 "species=[\"Al\"]",
99 "units=[\"angstrom\"]"
100 }
101 );
102
103 std::cout << result << "\n";
104 return 0;
105}
106*/
static size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp)
Definition kim_query.cpp:8
std::string kim_query(const std::string &query_function, const std::initializer_list< std::string > &extra_args={ "species=[]", })
Definition kim_query.cpp:22