Один ресурс API в C++
Многие API адресуют объект по идентификатору в конце пути.
Ответ - один JSON-объект, его разбирают так же, как
локальную строку, только источником служит тело
после успешного обмена libcurl. Чтение "/users/1"
на typicode возвращает пользователя с полем
name:
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <nlohmann/json.hpp>
size_t writeBody(
char* ptr,
size_t size,
size_t nmemb,
void* userdata
) {
auto* body = static_cast<std::string*>(userdata);
body->append(ptr, size * nmemb);
return size * nmemb;
}
int main() {
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL* curl = curl_easy_init();
std::string body;
curl_easy_setopt(
curl,
CURLOPT_URL,
"https://jsonplaceholder.typicode.com/users/1"
);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeBody);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
nlohmann::json user = nlohmann::json::parse(body);
std::cout << user.at("name").get<std::string>() << "\n";
}
curl_easy_cleanup(curl);
curl_global_cleanup();
return res == CURLE_OK ? 0 : 1;
}
Тот же путь с другим числом в конце дает другую
запись. Достаточно поменять сегмент адреса и снова
прочитать name из разобранного объекта:
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <nlohmann/json.hpp>
size_t writeBody(
char* ptr,
size_t size,
size_t nmemb,
void* userdata
) {
auto* body = static_cast<std::string*>(userdata);
body->append(ptr, size * nmemb);
return size * nmemb;
}
int main() {
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL* curl = curl_easy_init();
std::string body;
curl_easy_setopt(
curl,
CURLOPT_URL,
"https://jsonplaceholder.typicode.com/users/2"
);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeBody);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
nlohmann::json user = nlohmann::json::parse(body);
std::cout << user.at("id").get<int>() << "\n";
std::cout << user.at("name").get<std::string>() << "\n";
}
curl_easy_cleanup(curl);
curl_global_cleanup();
return res == CURLE_OK ? 0 : 1;
}