Modular REST API
π§© Modular REST API
Section titled βπ§© Modular REST APIβIn this example, weβll build a small REST API using Zuno with a modular structure. Youβll learn how to:
- Organize routes in separate files
- Return JSON responses
- Use
FetchContent
to fetch Zuno automatically
π§± Project Structure
Section titled βπ§± Project Structureβrest-api/βββ CMakeLists.txtβββ src/β βββ main.cppβ βββ routes/β βββ users.cppβββ include/ βββ routes/ βββ users.hpp
π CMakeLists.txt
Section titled βπ CMakeLists.txtβcmake_minimum_required(VERSION 3.16)project(rest_api)
set(CMAKE_CXX_STANDARD 20)
include(FetchContent)
FetchContent_Declare(zunoGIT_REPOSITORY https://github.com/ZunoFramework/zuno.gitGIT_TAG main)
FetchContent_MakeAvailable(zuno)
include_directories(include)
add_executable(rest-apisrc/main.cppsrc/routes/users.cpp)
target_link_libraries(rest-api PRIVATE zuno)
π src/main.cpp
Section titled βπ src/main.cppβ#include <zuno/zuno.hpp>#include "routes/users.hpp"
int main() {zuno::App app;
registerUserRoutes(app);
app.listen(3000);}
π src/routes/users.cpp
Section titled βπ src/routes/users.cppβ#include <zuno/zuno.hpp>#include "routes/users.hpp"
void registerUserRoutes(zuno::App& app) {app.get("/users", [](auto& req, auto& res) { res.json({ { "id", 1 }, { "name", "Alice" } });});
app.get("/users/:id", [](auto& req, auto& res) { std::string id = req.params["id"]; res.json({ { "id", id }, { "name", "User " + id } });});}
π include/routes/users.hpp
Section titled βπ include/routes/users.hppβ#pragma once#include <zuno/zuno.hpp>
void registerUserRoutes(zuno::App& app);
π Build & Run
Section titled βπ Build & Runβcmake -B buildcmake --build build./build/rest-api
Then test your API:
GET /users
β returns a list of usersGET /users/42
β returns user with ID 42
π§ Whatβs Next?
Section titled βπ§ Whatβs Next?βTry adding:
- Middleware like logging or authentication
- Rate Limiting to protect endpoints
- TLS Support for secure APIs
Zuno makes modular C++ web APIs feel naturalβwithout sacrificing performance or clarity.