External API Client
🌐 External API Client
Section titled “🌐 External API Client”In this example, you’ll build a Zuno microservice that fetches data from an external API (e.g. JSONPlaceholder) and returns it to the client. This is useful for:
- Proxying third-party APIs
- Aggregating data from multiple sources
- Building microservices that depend on external systems
📦 Requirements
Section titled “📦 Requirements”This example uses a lightweight HTTP client library. You can use any C++ HTTP client you prefer (e.g. cpr, Boost.Beast, or a custom wrapper around libcurl). For simplicity, we’ll assume you’re using cpr via FetchContent
.
🧱 Project Structure
Section titled “🧱 Project Structure”external-api-client/├── CMakeLists.txt└── main.cpp
📄 CMakeLists.txt
Section titled “📄 CMakeLists.txt”cmake_minimum_required(VERSION 3.16)project(external_api_client)
set(CMAKE_CXX_STANDARD 20)
include(FetchContent)
FetchContent_Declare(zunoGIT_REPOSITORY https://github.com/ZunoFramework/zuno.gitGIT_TAG main)
FetchContent_Declare(cprGIT_REPOSITORY https://github.com/libcpr/cpr.gitGIT_TAG 1.10.4)
FetchContent_MakeAvailable(zuno cpr)
add_executable(external-api main.cpp)target_link_libraries(external-api PRIVATE zuno cpr::cpr)
📄 main.cpp
Section titled “📄 main.cpp”#include <zuno/zuno.hpp>;#include <cpr/cpr.h>;
int main() {zuno::App app;
app.get("/posts/:id", [](auto& req, auto& res) { std::string id = req.params["id"]; auto response = cpr::Get(cpr::Url{"https://jsonplaceholder.typicode.com/posts/" + id});
if (response.status_code == 200) { res.status(200).send(response.text); } else { res.status(502).send("Failed to fetch external data"); }});
app.listen(3000);}
🧪 Test the Microservice
Section titled “🧪 Test the Microservice”curl http://localhost:3000/posts/1
You should receive a JSON response from the external API, proxied through your Zuno server.
🧭 What’s Next?
Section titled “🧭 What’s Next?”- Add Caching to reduce external load
- Use Error Handling for better fallback logic
- Secure the endpoint with Authentication
Zuno makes it easy to build microservices that talk to the outside world—securely and efficiently.