Convert Figma logo to code with AI

microsoft logocpprestsdk

The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact with services.

7,994
1,654
7,994
862

Top Related Projects

A C++ header-only HTTP/HTTPS server and client library

42,154

JSON for Modern C++

14,146

A fast JSON parser/generator for C++ with both SAX/DOM style API

C++ websocket client/server library

4,904

Asio C++ Library

GoogleTest - Google Testing and Mocking Framework

Quick Overview

The C++ REST SDK (cpprestsdk) is a Microsoft project that provides a modern asynchronous C++ API for cloud-based client-server communication. It supports HTTP client/server, JSON, URI, and asynchronous streams, making it easier to consume and produce REST APIs and other web services.

Pros

  • Cross-platform support (Windows, Linux, macOS, iOS, Android)
  • Built-in support for JSON parsing and serialization
  • Asynchronous programming model using PPL tasks
  • Comprehensive HTTP client and server functionality

Cons

  • Learning curve for developers unfamiliar with asynchronous programming
  • Limited documentation and examples compared to some other libraries
  • Dependency on Boost libraries, which can increase project complexity
  • Some users report performance issues with large-scale applications

Code Examples

  1. Making an HTTP GET request:
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>

using namespace web;
using namespace web::http;
using namespace web::http::client;

pplx::task<void> make_request() {
    http_client client(U("https://api.example.com"));
    return client.request(methods::GET, U("/users"))
        .then([](http_response response) {
            return response.extract_json();
        })
        .then([](web::json::value json) {
            std::cout << json.serialize() << std::endl;
        });
}
  1. Creating a simple HTTP server:
#include <cpprest/http_listener.h>

using namespace web;
using namespace web::http;
using namespace web::http::experimental::listener;

void handle_get(http_request request) {
    json::value response;
    response[U("message")] = json::value::string(U("Hello, World!"));
    request.reply(status_codes::OK, response);
}

int main() {
    http_listener listener(U("http://localhost:8080"));
    listener.support(methods::GET, handle_get);
    listener.open().wait();
    return 0;
}
  1. Parsing and creating JSON:
#include <cpprest/json.h>

using namespace web;

void json_example() {
    json::value obj;
    obj[U("name")] = json::value::string(U("John Doe"));
    obj[U("age")] = json::value::number(30);
    obj[U("isStudent")] = json::value::boolean(false);

    std::wcout << obj.serialize() << std::endl;

    json::value parsed = json::value::parse(U(R"({"key": "value"})"));
    std::wcout << parsed[U("key")].as_string() << std::endl;
}

Getting Started

  1. Install cpprestsdk using vcpkg:

    vcpkg install cpprestsdk
    
  2. Include the necessary headers in your C++ file:

    #include <cpprest/http_client.h>
    #include <cpprest/json.h>
    
  3. Link against the cpprestsdk library in your build system.

  4. Use the library in your code:

    #include <cpprest/http_client.h>
    #include <iostream>
    
    using namespace web;
    using namespace web::http;
    using namespace web::http::client;
    
    int main() {
        http_client client(U("https://api.github.com"));
        client.request(methods::GET, U("/repos/microsoft/cpprestsdk"))
            .then([](http_response response) {
                return response.extract_json();
            })
            .then([](web::json::value json) {
                std::cout << "Repository name: " << json[U("name")].as_string() << std::endl;
            })
            .wait();
        return 0;
    }
    

Competitor Comparisons

A C++ header-only HTTP/HTTPS server and client library

Pros of cpp-httplib

  • Lightweight and header-only library, easy to integrate
  • Simple and intuitive API for both client and server
  • No external dependencies required

Cons of cpp-httplib

  • Limited features compared to cpprestsdk's comprehensive functionality
  • Less robust for large-scale, enterprise-level applications
  • Fewer platform-specific optimizations

Code Comparison

cpp-httplib:

#include <httplib.h>

int main() {
    httplib::Server svr;
    svr.Get("/hi", [](const httplib::Request&, httplib::Response& res) {
        res.set_content("Hello World!", "text/plain");
    });
    svr.listen("localhost", 8080);
}

cpprestsdk:

#include <cpprest/http_listener.h>

int main() {
    web::http::experimental::listener::http_listener listener("http://localhost:8080");
    listener.support(web::http::methods::GET, [](web::http::http_request request) {
        request.reply(web::http::status_codes::OK, "Hello World!");
    });
    listener.open().wait();
}

Both libraries provide simple ways to create HTTP servers, but cpp-httplib's API is more straightforward. However, cpprestsdk offers more advanced features and better support for asynchronous operations, making it more suitable for complex applications.

42,154

JSON for Modern C++

Pros of json

  • Lightweight and header-only library, easy to integrate
  • Extensive documentation and examples
  • Modern C++ design with intuitive API

Cons of json

  • Limited to JSON processing, lacks broader networking capabilities
  • May require additional libraries for HTTP requests or WebSocket support

Code Comparison

json:

#include <nlohmann/json.hpp>
using json = nlohmann::json;

json j = {
  {"name", "John"},
  {"age", 30},
  {"city", "New York"}
};
std::string s = j.dump();

cpprestsdk:

#include <cpprest/json.h>
using namespace web;

json::value j;
j["name"] = json::value::string("John");
j["age"] = json::value::number(30);
j["city"] = json::value::string("New York");
std::string s = j.serialize();

Summary

json is a specialized JSON library offering a modern, user-friendly API for JSON manipulation. cpprestsdk provides a more comprehensive set of tools for web and cloud-based applications, including HTTP client/server, JSON, and WebSocket support. Choose json for lightweight JSON processing, and cpprestsdk for broader networking capabilities in C++ applications.

14,146

A fast JSON parser/generator for C++ with both SAX/DOM style API

Pros of rapidjson

  • Faster parsing and serialization performance
  • Lighter memory footprint
  • More focused on JSON processing, potentially simpler for JSON-specific tasks

Cons of rapidjson

  • Limited to JSON processing, while cpprestsdk offers broader functionality
  • Less comprehensive documentation and community support
  • Fewer high-level abstractions for complex operations

Code Comparison

rapidjson:

Document d;
d.Parse(json);
std::string name = d["name"].GetString();
int age = d["age"].GetInt();

cpprestsdk:

json::value obj = json::value::parse(json);
std::string name = obj["name"].as_string();
int age = obj["age"].as_integer();

Both libraries provide straightforward JSON parsing, but rapidjson's approach is more low-level and potentially faster, while cpprestsdk offers a more abstracted interface.

rapidjson is ideal for projects primarily focused on high-performance JSON processing, whereas cpprestsdk is better suited for applications requiring a broader range of REST and HTTP functionalities alongside JSON handling.

The choice between these libraries depends on the specific requirements of your project, balancing factors such as performance needs, feature set, and development complexity.

C++ websocket client/server library

Pros of websocketpp

  • Lightweight and focused solely on WebSocket functionality
  • Header-only library, simplifying integration into projects
  • More flexible and customizable for specific WebSocket needs

Cons of websocketpp

  • Lacks the broader feature set of cpprestsdk (e.g., HTTP client/server, JSON parsing)
  • May require additional libraries for features like SSL support
  • Less active development and community support compared to cpprestsdk

Code Comparison

websocketpp:

#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>

typedef websocketpp::server<websocketpp::config::asio> server;

server echo_server;
echo_server.set_message_handler([](websocketpp::connection_hdl hdl, server::message_ptr msg) {
    // Handle WebSocket message
});

cpprestsdk:

#include <cpprest/ws_client.h>

web::websockets::client::websocket_client client;
client.connect(U("wss://echo.websocket.org")).then([&client]() {
    return client.send(U("Hello, WebSocket!"));
}).then([&client]() {
    return client.receive();
}).then([](web::websockets::client::websocket_incoming_message msg) {
    // Handle WebSocket message
});

Both libraries provide WebSocket functionality, but cpprestsdk offers a more comprehensive set of features for web-related tasks, while websocketpp focuses specifically on WebSocket implementation with greater customization options.

4,904

Asio C++ Library

Pros of Asio

  • Lightweight and header-only library, making it easy to integrate into projects
  • Provides a more low-level, flexible API for network programming
  • Supports both synchronous and asynchronous operations

Cons of Asio

  • Steeper learning curve due to its lower-level nature
  • Less built-in functionality for higher-level protocols (e.g., HTTP, WebSockets)

Code Comparison

Asio example:

asio::io_context io_context;
asio::ip::tcp::socket socket(io_context);
asio::ip::tcp::resolver resolver(io_context);
asio::async_connect(socket, resolver.resolve("example.com", "80"),
    [](const asio::error_code& ec, const asio::ip::tcp::endpoint&) {
        // Handle connection
    });

C++ REST SDK example:

http_client client(U("http://example.com"));
client.request(methods::GET, U("/api/data"))
    .then([](http_response response) {
        // Handle response
    });

The Asio example demonstrates lower-level socket operations, while the C++ REST SDK example shows a higher-level HTTP request. Asio provides more control over the networking details, while C++ REST SDK offers a more abstracted, user-friendly API for common web operations.

GoogleTest - Google Testing and Mocking Framework

Pros of googletest

  • More focused on unit testing, providing a comprehensive framework for C++ testing
  • Wider adoption and community support in the C++ ecosystem
  • Easier to set up and integrate into existing C++ projects

Cons of googletest

  • Limited to testing functionality, unlike cpprestsdk which offers broader features
  • May require additional libraries for certain types of tests (e.g., mocking)
  • Less suitable for projects requiring REST client/server capabilities

Code Comparison

googletest example:

TEST(FactorialTest, HandlesZeroInput) {
  EXPECT_EQ(Factorial(0), 1);
}

TEST(FactorialTest, HandlesPositiveInput) {
  EXPECT_EQ(Factorial(1), 1);
  EXPECT_EQ(Factorial(2), 2);
  EXPECT_EQ(Factorial(3), 6);
}

cpprestsdk example:

http_client client(U("http://example.com"));
client.request(methods::GET, U("/api/data"))
.then([](http_response response) {
    return response.extract_json();
})
.then([](json::value json) {
    // Process JSON data
});

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

cpprestsdk is in maintenance mode and we do not recommend its use in new projects. We will continue to fix critical bugs and address security issues.

Welcome!

The C++ REST SDK is a Microsoft project for cloud-based client-server communication in native code using a modern asynchronous C++ API design. This project aims to help C++ developers connect to and interact with services.

Getting Started

Vcpkg package
Homebrew package
Ubuntu 18.04 package
Fedora Rawhide package
openSUSE Tumbleweed package
Debian Testing package

Build Status

With vcpkg on Windows

PS> vcpkg install cpprestsdk cpprestsdk:x64-windows

With apt-get on Debian/Ubuntu

$ sudo apt-get install libcpprest-dev

With dnf on Fedora

$ sudo dnf install cpprest-devel

With brew on OSX

$ brew install cpprestsdk

With NuGet on Windows for Android

PM> Install-Package cpprestsdk.android

For other platforms, install options, how to build from source, and more, take a look at our Documentation.

Once you have the library, look at our tutorial to use the http_client. It walks through how to setup a project to use the C++ Rest SDK and make a basic Http request.

To use from CMake:

cmake_minimum_required(VERSION 3.9)
project(main)

find_package(cpprestsdk REQUIRED)

add_executable(main main.cpp)
target_link_libraries(main PRIVATE cpprestsdk::cpprest)

What's in the SDK:

  • Features - HTTP client/server, JSON, URI, asynchronous streams, WebSockets client, oAuth
  • PPL Tasks - A powerful model for composing asynchronous operations based on C++ 11 features
  • Platforms - Windows desktop, Windows Store (UWP), Linux, OS X, Unix, iOS, and Android
  • Support for Visual Studio 2015 and 2017 with debugger visualizers

Contribute Back!

Is there a feature missing that you'd like to see, or found a bug that you have a fix for? Or do you have an idea or just interest in helping out in building the library? Let us know and we'd love to work with you. For a good starting point on where we are headed and feature ideas, take a look at our requested features and bugs.

Big or small we'd like to take your contributions back to help improve the C++ Rest SDK for everyone.

Having Trouble?

We'd love to get your review score, whether good or bad, but even more than that, we want to fix your problem. If you submit your issue as a Review, we won't be able to respond to your problem and ask any follow-up questions that may be necessary. The most efficient way to do that is to open an issue in our issue tracker.

Quick Links

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.