CPPI is a modern, header-only C++ HTTP server and client library designed for simplicity, performance, and ease of use with built-in support for streaming, JSON handling, and high-performance multi-threaded server operations.
- Multi-threaded server with configurable thread pool
- Streaming support for large files and unlimited request/response sizes
- Connection pooling and efficient memory management
- Non-blocking I/O with optimized buffer management
- Header-only library - just include and go!
- Express.js-inspired API for familiar web development patterns
- Automatic content-type detection based on file extensions
- Built-in JSON support using nlohmann/json
- Route parameters and wildcards (e.g.,
/users/:id) - Middleware support for request/response processing
- Static file serving with automatic streaming for large files
- Custom error handling and status codes
- All HTTP methods: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
- Request/Response streaming for handling large payloads
- File upload/download with progress tracking
- Custom headers and query parameters
- Form data and multipart support
CPPI is designed for maximum simplicity. No complex configuration, no user loops, no thread management:
#include "cppi.hpp"
using namespace cppi;
int main() {
Server server(8080);
server.route()
.get("/", [](const Request& req, Response& res) {
res.text("Hello, World!");
});
server.run(); // That's it! Runs until Ctrl+C
return 0;
}Key Benefits:
- No user loops required -
server.run()handles everything - Automatic signal handling - Graceful shutdown with Ctrl+C
- Zero configuration - Works out of the box
- Production ready - Built-in thread pooling and connection management
Option A: One-command setup (Recommended)
git clone --recurse-submodules --shallow-submodules https://github.com/philopaterwaheed/cppi.git
cd cppiOption B: Clone and setup manually
git clone https://github.com/philopaterwaheed/cppi.git
git submodule update --init --depth 1Why shallow submodules? Using
--shallow-submodulesensures nlohmann/json is cloned with depth 1, reducing download time and disk space usage from ~50MB to ~2MB.
- Include in your project:
#include "cppi.hpp"
using namespace cppi;- Compile with C++17:
g++ -std=c++17 -I. your_file.cpp -o your_app# Option 1: Add as subdirectory
add_subdirectory(cppi)
target_link_libraries(your_target PRIVATE cppi::cppi)
# Option 2: Find installed package
find_package(cppi REQUIRED)
target_link_libraries(your_target PRIVATE cppi::cppi)mkdir build && cd build
cmake ..
make
sudo make install#include "cppi.hpp"
using namespace cppi;
int main() {
Server server(8080);
server.route()
.get("/", [](const Request& req, Response& res) {
res.text("Hello, World!");
})
.get("/api/users/:id", [](const Request& req, Response& res) {
std::string userId = req.getParam("id");
nlohmann::json user = {
{"id", userId},
{"name", "User " + userId}
};
res.json(user);
})
.post("/api/data", [](const Request& req, Response& res) {
// Handle JSON data
auto data = nlohmann::json::parse(req.body);
res.json({{"received", data}, {"status", "success"}});
});
// Start server and run until Ctrl+C
server.run();
return 0;
}#include "cppi.hpp"
using namespace cppi;
int main() {
Client client;
// GET request
auto response = client.get("httpbin.org", 80, "/get");
std::cout << "Status: " << static_cast<int>(response.status) << std::endl;
// POST with JSON
nlohmann::json data = {{"name", "John"}, {"age", 30}};
auto postResp = client.post("api.example.com", 443, "/users", data);
// Download file
client.downloadFile("http://example.com/file.zip", "local_file.zip");
return 0;
}Server(int port = 8080, size_t maxConnections = 1000, size_t threadCount = 0)port: Server port (default: 8080)maxConnections: Maximum concurrent connections (default: 1000)threadCount: Worker threads (default: hardware concurrency)
| Method | Description |
|---|---|
run() |
Start server and block until stopped (simplest usage) |
runAsync() |
Start server in non-blocking mode |
stop() |
Stop the server gracefully |
isRunning() |
Check if server is currently running |
waitForStop() |
Wait for server to stop (use with runAsync) |
route() |
Get router for adding routes |
printStats() |
Display server performance statistics |
Simple Blocking Server (Recommended for most cases):
Server server(8080);
server.route().get("/", handler);
server.run(); // Blocks until Ctrl+CNon-blocking Server (For custom monitoring/control):
Server server(8080);
server.route().get("/", handler);
server.runAsync(); // Returns immediately
while (server.isRunning()) {
// Custom monitoring logic
server.printStats();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
server.waitForStop();Router& get(const std::string& path, Handler handler)
Router& post(const std::string& path, Handler handler)
Router& put(const std::string& path, Handler handler)
Router& del(const std::string& path, Handler handler) // DELETE
Router& patch(const std::string& path, Handler handler)
Router& head(const std::string& path, Handler handler)
Router& options(const std::string& path, Handler handler)- Static routes:
/api/users - Parameters:
/users/:id→ access viareq.getParam("id") - Wildcards:
/files/*→ matches any path starting with/files/
Router& use(Middleware middleware)| Property | Type | Description |
|---|---|---|
method |
Method |
HTTP method (GET, POST, etc.) |
path |
std::string |
Request path |
query |
std::string |
Raw query string |
headers |
std::unordered_map<std::string, std::string> |
HTTP headers |
params |
std::unordered_map<std::string, std::string> |
Route parameters |
queryParams |
std::unordered_map<std::string, std::string> |
Query parameters |
body |
std::string |
Request body |
std::string getHeader(const std::string& name) const
std::string getParam(const std::string& name) const
std::string getQuery(const std::string& name) const
bool hasHeader(const std::string& name) const
bool hasParam(const std::string& name) const
bool hasQuery(const std::string& name) const
// Streaming support
bool hasStreamingBody() const
void streamBody(std::function<bool(const char*, size_t)> callback) const
bool saveBodyToFile(const std::string& filename) constResponse& setStatus(Status status) // Set HTTP status codeResponse& setHeader(const std::string& name, const std::string& value)
Response& setContentType(const std::string& contentType)
std::string getHeader(const std::string& name) const
bool hasHeader(const std::string& name) constResponse& text(const std::string& content, bool isPath = false)
Response& html(const std::string& content, bool isPath = true)
Response& json(nlohmann::json jsonObj)
Response& send(const std::string& data)Response& streamFile(const std::string& filename)
Response& streamCallback(types::StreamDataCallback callback)
Response& streamReader(std::shared_ptr<helpers::StreamReader> reader)// URL-based requests
Response get(const std::string& url, const Headers& headers = {})
Response post(const std::string& url, const BodyVariant& body = {}, const Headers& headers = {})
Response put(const std::string& url, const BodyVariant& body = {}, const Headers& headers = {})
Response del(const std::string& url, const Headers& headers = {})
Response patch(const std::string& url, const BodyVariant& body = {}, const Headers& headers = {})
Response head(const std::string& url, const Headers& headers = {})
// Host/Port/Path-based requests
Response get(const std::string& host, int port, const std::string& path, const Headers& headers = {})
Response post(const std::string& host, int port, const std::string& path, const BodyVariant& body = {}, const Headers& headers = {})
// ... similar for other methodsbool downloadFile(const std::string& url, const std::string& localPath, const Headers& headers = {})
Response uploadFile(const std::string& url, const std::string& filePath, const Headers& headers = {})
bool ping(const std::string& url)Response postStream(const std::string& url, std::shared_ptr<helpers::StreamReader> reader, const Headers& headers = {})
Response putStream(const std::string& url, std::shared_ptr<helpers::StreamReader> reader, const Headers& headers = {})
bool downloadFileStream(const std::string& url, const std::string& localPath, const Headers& headers = {})
void streamResponse(const std::string& url, std::function<bool(const char*, size_t)> callback, const Headers& headers = {})CPPI automatically handles streaming for large files and unlimited request/response sizes:
server.route()
.get("/download/:filename", [](const Request& req, Response& res) {
std::string filename = req.getParam("filename");
res.streamFile("files/" + filename); // Automatic streaming for large files
})
.get("/live-data", [](const Request& req, Response& res) {
res.streamCallback([](char* buffer, size_t maxSize) -> bool {
// Generate data on-the-fly
static int counter = 0;
std::string data = "Data chunk " + std::to_string(++counter) + "\n";
std::memcpy(buffer, data.c_str(), std::min(data.size(), maxSize));
return counter < 100; // Stop after 100 chunks
});
});Client client;
// Stream large file upload
client.uploadFile("http://api.example.com/upload", "large_file.zip");
// Stream response processing
client.streamResponse("http://api.example.com/data",
[](const char* data, size_t size) -> bool {
// Process data chunk by chunk
std::cout.write(data, size);
return true; // Continue streaming
});// CORS middleware
auto corsMiddleware = [](const Request& req, Response& res) -> bool {
res.setHeader("Access-Control-Allow-Origin", "*")
.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
return true; // Continue to next middleware/route
};
// Authentication middleware
auto authMiddleware = [](const Request& req, Response& res) -> bool {
if (!req.hasHeader("Authorization")) {
res.setStatus(Status::UNAUTHORIZED).json({{"error", "Authentication required"}});
return false; // Stop processing
}
return true;
};
server.route()
.use(corsMiddleware)
.use(authMiddleware)
.get("/protected", [](const Request& req, Response& res) {
res.json({{"message", "Access granted"}});
});#include "cppi.hpp"
Server server(8080);
// Serve static files from 'public' directory
server.route().use(staticFiles("public/"));
// Manual static file serving with custom logic
server.route()
.get("/assets/*", [](const Request& req, Response& res) {
std::string filePath = "assets" + req.path.substr(7); // Remove "/assets"
if (std::filesystem::exists(filePath)) {
res.streamFile(filePath); // Automatic content-type detection
} else {
res.setStatus(Status::NOT_FOUND).text("File not found");
}
});server.route()
.get("/api/user/:id", [](const Request& req, Response& res) {
try {
int userId = std::stoi(req.getParam("id"));
// Database lookup logic here
if (userId <= 0) {
throw errors::BadRequestError("Invalid user ID");
}
// User not found
if (/* user not exists */) {
throw errors::NotFoundError("User not found");
}
nlohmann::json user = {{"id", userId}, {"name", "John Doe"}};
res.json(user);
} catch (const errors::HttpError& e) {
res.setStatus(static_cast<Status>(e.statusCode()))
.json({{"error", e.what()}});
} catch (const std::exception& e) {
res.setStatus(Status::INTERNAL_SERVER_ERROR)
.json({{"error", "Internal server error"}});
}
});- Configurable thread pool size
- Automatic load balancing
- Connection limits to prevent overload
- Streaming prevents loading large files into memory
- Efficient buffer management
- Connection pooling for client requests
server.printStats(); // Display performance metricsOutput:
=== Server Stats ===
Uptime: 3600 seconds
Active connections: 45
Total requests: 12847
Pending tasks: 3
Requests/second: 3.57
The library includes comprehensive examples that demonstrate all features:
# Build examples
mkdir build && cd build
cmake ..
make
# Run tests
./simple_test # Basic functionality test
./example_client # HTTP client examples
./example_server # HTTP server examples
./example_streaming # Streaming examplesCPPI provides comprehensive error handling with custom exception types:
try {
Client client;
auto response = client.get("invalid-url");
} catch (const errors::NetworkError& e) {
std::cerr << "Network error: " << e.what() << std::endl;
} catch (const errors::TimeoutError& e) {
std::cerr << "Request timeout: " << e.what() << std::endl;
} catch (const errors::HttpError& e) {
std::cerr << "HTTP error " << e.statusCode() << ": " << e.what() << std::endl;
}errors::HttpError- Base HTTP error with status codeerrors::BadRequestError- 400 Bad Requesterrors::UnauthorizedError- 401 Unauthorizederrors::ForbiddenError- 403 Forbiddenerrors::NotFoundError- 404 Not Founderrors::MethodNotAllowedError- 405 Method Not Allowederrors::ValidationError- 422 Unprocessable Entityerrors::TooManyRequestsError- 429 Too Many Requestserrors::InternalServerError- 500 Internal Server Errorerrors::NetworkError- Network connectivity issueserrors::TimeoutError- Request timeouterrors::FileReadError- File system errors
- C++17 or later
- CMake 3.15+ (for CMake builds)
- Threading support (pthreads on Unix, native on Windows)
- Linux (tested on Ubuntu, CentOS, Alpine)
- Windows (MSVC, MinGW)
- macOS (Clang)
- FreeBSD, OpenBSD
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
git clone --recurse-submodules --shallow-submodules https://github.com/philopaterwaheed/cppi.git
cd cppi
mkdir build && cd build
cmake -DCPPI_BUILD_EXAMPLES=ON ..
make- WebSocket support
- HTTP/2 support
- SSL/TLS encryption
- Built-in rate limiting
- Database integration helpers
- WebRTC support
- Prometheus metrics export
- Docker container examples
- Built on nlohmann/json for JSON support
- Inspired by Express.js API design
Made with ❤️
