Convert Figma logo to code with AI

libcpr logocpr

C++ Requests: Curl for People, a spiritual port of Python Requests.

6,518
928
6,518
70

Top Related Projects

35,356

A command line tool and library for transferring data with URL syntax, supporting DICT, FILE, FTP, FTPS, GOPHER, GOPHERS, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S, RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET, TFTP, WS and WSS. libcurl offers a myriad of powerful features

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.

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

Async++ concurrency framework for C++11

6,524

C++ Requests: Curl for People, a spiritual port of Python Requests.

42,154

JSON for Modern C++

Quick Overview

CPR (C++ Requests) is a modern, feature-rich HTTP client library for C++. It provides a simple and intuitive API inspired by Python's requests library, making it easy to perform HTTP requests in C++ applications. CPR is designed to be lightweight, fast, and easy to use.

Pros

  • Simple and intuitive API, similar to Python's requests library
  • Cross-platform support (Windows, macOS, Linux)
  • Built-in SSL support with OpenSSL
  • Supports various HTTP methods, headers, and authentication types

Cons

  • Dependency on libcurl, which may increase project size
  • Limited documentation compared to some other HTTP libraries
  • Potential performance overhead compared to lower-level libraries
  • May require additional setup for certain features (e.g., SSL support)

Code Examples

  1. Simple GET request:
#include <cpr/cpr.h>
#include <iostream>

int main() {
    cpr::Response r = cpr::Get(cpr::Url{"https://api.github.com/repos/libcpr/cpr"});
    std::cout << "Status code: " << r.status_code << std::endl;
    std::cout << "Response body: " << r.text << std::endl;
    return 0;
}
  1. POST request with JSON payload:
#include <cpr/cpr.h>

int main() {
    cpr::Response r = cpr::Post(cpr::Url{"https://api.example.com/users"},
                                cpr::Header{{"Content-Type", "application/json"}},
                                cpr::Body{R"({"name": "John Doe", "email": "john@example.com"})"});
    return 0;
}
  1. Asynchronous request:
#include <cpr/cpr.h>
#include <iostream>

int main() {
    auto future = cpr::GetAsync(cpr::Url{"https://api.github.com/repos/libcpr/cpr"});
    // Do other work here...
    cpr::Response r = future.get();
    std::cout << "Status code: " << r.status_code << std::endl;
    return 0;
}

Getting Started

To use CPR in your project, follow these steps:

  1. Install CPR using a package manager or build from source.
  2. Include the CPR header in your C++ file:
    #include <cpr/cpr.h>
    
  3. Link against the CPR library when compiling your project.
  4. Use the CPR API to make HTTP requests in your code:
    cpr::Response r = cpr::Get(cpr::Url{"https://api.example.com"});
    

For more detailed installation and usage instructions, refer to the official CPR documentation.

Competitor Comparisons

35,356

A command line tool and library for transferring data with URL syntax, supporting DICT, FILE, FTP, FTPS, GOPHER, GOPHERS, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S, RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET, TFTP, WS and WSS. libcurl offers a myriad of powerful features

Pros of curl

  • Mature and widely used project with extensive documentation
  • Supports a vast array of protocols and features
  • Cross-platform compatibility and portability

Cons of curl

  • C-based API can be complex for modern C++ developers
  • Requires manual memory management
  • Steeper learning curve for beginners

Code Comparison

curl:

CURL *curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
  res = curl_easy_perform(curl);
  curl_easy_cleanup(curl);
}

cpr:

#include <cpr/cpr.h>

auto r = cpr::Get(cpr::Url{"https://example.com"});
std::cout << r.text << std::endl;

The code comparison demonstrates the simplicity of cpr compared to curl. cpr provides a more modern, C++-friendly API with automatic resource management, while curl requires manual initialization, option setting, and cleanup.

cpr builds on top of curl, offering a higher-level abstraction that simplifies HTTP requests in C++. It provides a more intuitive interface for developers familiar with modern C++ practices, while still leveraging the robust foundation of curl.

Both libraries have their merits, with curl offering more extensive protocol support and cpr providing a more streamlined experience for C++ developers focusing on HTTP requests.

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.

Pros of cpprestsdk

  • More comprehensive library with support for various protocols (HTTP, WebSockets, JSON)
  • Better suited for large-scale enterprise applications
  • Extensive documentation and Microsoft support

Cons of cpprestsdk

  • Larger footprint and potentially steeper learning curve
  • Slower compilation times due to its size and complexity
  • May be overkill for simple HTTP requests

Code Comparison

cpprestsdk:

#include <cpprest/http_client.h>

auto response = client.request(methods::GET, U("/api/data")).get();
auto json = response.extract_json().get();

cpr:

#include <cpr/cpr.h>

auto response = cpr::Get(cpr::Url{"https://api.example.com/data"});
auto json = nlohmann::json::parse(response.text);

Summary

cpprestsdk is a more comprehensive library suitable for complex, enterprise-level applications, while cpr is lightweight and focused primarily on HTTP requests. cpprestsdk offers broader functionality but comes with a larger footprint, while cpr is simpler to use for basic HTTP operations. The choice between them depends on the specific requirements of your project and the level of complexity you need to handle.

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

Pros of cpp-httplib

  • Header-only library, making it easier to integrate into projects
  • Supports both client and server-side HTTP/HTTPS functionality
  • Lightweight with minimal dependencies

Cons of cpp-httplib

  • Less feature-rich compared to cpr, especially for advanced use cases
  • May require more manual configuration for complex scenarios
  • Limited built-in support for asynchronous operations

Code Comparison

cpp-httplib:

#include <httplib.h>

int main() {
    httplib::Client cli("http://example.com");
    auto res = cli.Get("/");
    if (res && res->status == 200) {
        std::cout << res->body << std::endl;
    }
}

cpr:

#include <cpr/cpr.h>

int main() {
    auto r = cpr::Get(cpr::Url{"http://example.com"});
    if (r.status_code == 200) {
        std::cout << r.text << std::endl;
    }
}

Both libraries offer straightforward ways to make HTTP requests, but cpr provides a more modern and intuitive API. cpp-httplib's approach is more traditional and may be familiar to developers used to working with raw HTTP libraries.

Async++ concurrency framework for C++11

Pros of asyncplusplus

  • Focuses on asynchronous programming and parallel task execution
  • Provides a more comprehensive set of asynchronous primitives (e.g., tasks, parallel_for, when_all)
  • Designed for high-performance concurrent programming

Cons of asyncplusplus

  • Limited to asynchronous programming, lacks HTTP-specific features
  • May have a steeper learning curve for developers not familiar with concurrent programming concepts
  • Less active development and smaller community compared to cpr

Code Comparison

asyncplusplus example:

#include <async++.h>

async::parallel_for(0, 100, [](int i) {
    // Perform parallel operation
});

cpr example:

#include <cpr/cpr.h>

auto r = cpr::Get(cpr::Url{"https://api.example.com"});
std::cout << r.text << std::endl;

Summary

asyncplusplus is a library focused on asynchronous and parallel programming in C++, offering advanced concurrency features. cpr, on the other hand, is primarily an HTTP client library that simplifies making HTTP requests. While asyncplusplus provides powerful tools for concurrent programming, cpr excels in handling HTTP communications with a simpler API. The choice between the two depends on the specific requirements of your project: asyncplusplus for complex asynchronous operations, or cpr for straightforward HTTP interactions.

6,524

C++ Requests: Curl for People, a spiritual port of Python Requests.

Pros of cpr

  • Actively maintained with regular updates and bug fixes
  • Extensive documentation and examples for easy integration
  • Wide range of features including SSL support and custom headers

Cons of cpr

  • Larger codebase and dependencies may increase project size
  • Learning curve for advanced features can be steeper
  • Some users report occasional performance issues with large requests

Code Comparison

cpr example:

#include <cpr/cpr.h>

auto r = cpr::Get(cpr::Url{"https://api.github.com/repos/libcpr/cpr"});
std::cout << r.text << std::endl;

cpr> example:

#include <cpr/cpr.h>

auto r = cpr::Get(cpr::Url{"https://api.github.com/repos/libcpr/cpr>"});
std::cout << r.text << std::endl;

Note: The code comparison shows identical usage for both repositories, as cpr> is not a separate project but rather a typo or mistake in the repository name. The correct repository is libcpr/cpr, and there is no distinct libcpr/cpr> project for comparison.

42,154

JSON for Modern C++

Pros of json

  • Header-only library, making it easy to integrate into projects
  • Extensive documentation and examples
  • Wide range of JSON manipulation features, including serialization and deserialization

Cons of json

  • Larger compile times due to heavy template usage
  • May have a steeper learning curve for beginners compared to cpr's simpler API

Code Comparison

json:

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

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

cpr:

#include <cpr/cpr.h>

auto r = cpr::Get(cpr::Url{"https://api.example.com/data"},
                  cpr::Authentication{"user", "pass"},
                  cpr::Parameters{{"key", "value"}});
std::string response_body = r.text;

While json focuses on JSON data manipulation, cpr is primarily used for HTTP requests. json offers more comprehensive JSON handling, while cpr provides a simpler interface for making HTTP requests. The choice between them depends on the specific needs of your project, whether it's primarily JSON processing or HTTP communication.

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

C++ Requests: Curl for People

Documentation CI Gitter

Announcements

Supported Releases

ReleaseMin. C++ StandardStatusNotes
mastercpp17alt text
1.10.xcpp17alt text
1.9.xcpp11alt textSupported until 01.01.2025
<= 1.8.xcpp11alt text

TLDR

C++ Requests is a simple wrapper around libcurl inspired by the excellent Python Requests project.

Despite its name, libcurl's easy interface is anything but, and making mistakes, misusing it is a common source of error and frustration. Using the more expressive language facilities of C++17 (or C++11 in case you use cpr < 1.10.0), this library captures the essence of making network calls into a few concise idioms.

Here's a quick GET request:

#include <cpr/cpr.h>

int main(int argc, char** argv) {
    cpr::Response r = cpr::Get(cpr::Url{"https://api.github.com/repos/whoshuu/cpr/contributors"},
                      cpr::Authentication{"user", "pass", cpr::AuthMode::BASIC},
                      cpr::Parameters{{"anon", "true"}, {"key", "value"}});
    r.status_code;                  // 200
    r.header["content-type"];       // application/json; charset=utf-8
    r.text;                         // JSON text string
    return 0;
}

And here's less functional, more complicated code, without cpr.

Documentation

Documentation
You can find the latest documentation here. It's a work in progress, but it should give you a better idea of how to use the library than the tests currently do.

Features

C++ Requests currently supports:

  • Custom headers
  • Url encoded parameters
  • Url encoded POST values
  • Multipart form POST upload
  • File POST upload
  • Basic authentication
  • Bearer authentication
  • Digest authentication
  • NTLM authentication
  • Connection and request timeout specification
  • Timeout for low speed connection
  • Asynchronous requests
  • :cookie: support!
  • Proxy support
  • Callback interfaces
  • PUT methods
  • DELETE methods
  • HEAD methods
  • OPTIONS methods
  • PATCH methods
  • Thread Safe access to libCurl
  • OpenSSL and WinSSL support for HTTPS requests

Planned

For a quick overview about the planed features, have a look at the next Milestones.

Usage

CMake

fetch_content:

If you already have a CMake project you need to integrate C++ Requests with, the primary way is to use fetch_content. Add the following to your CMakeLists.txt.

include(FetchContent)
FetchContent_Declare(cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git
                         GIT_TAG 3b15fa82ea74739b574d705fea44959b58142eb8) # Replace with your desired git commit from: https://github.com/libcpr/cpr/releases
FetchContent_MakeAvailable(cpr)

This will produce the target cpr::cpr which you can link against the typical way:

target_link_libraries(your_target_name PRIVATE cpr::cpr)

That should do it! There's no need to handle libcurl yourself. All dependencies are taken care of for you.
All of this can be found in an example here.

find_package():

If you prefer not to use fetch_content, you can download, build, and install the library and then use CMake find_package() function to integrate it into a project.

Note: this feature is feasible only if CPR_USE_SYSTEM_CURL is set. (see #645)

git clone https://github.com/libcpr/cpr.git
cd cpr && mkdir build && cd build
cmake .. -DCPR_USE_SYSTEM_CURL=ON
cmake --build . --parallel
sudo cmake --install .

Build Static Library

As an alternative if you want to switch between a static or shared version of cpr use '-DBUILD_SHARED_LIBS=ON/OFF'.

git clone https://github.com/libcpr/cpr.git
cd cpr && mkdir build && cd build
cmake .. -DCPR_USE_SYSTEM_CURL=ON -DBUILD_SHARED_LIBS=OFF
cmake --build . --parallel
sudo cmake --install .

In your CMakeLists.txt:

find_package(cpr REQUIRED)
add_executable(your_target_name your_target_name.cpp)
target_link_libraries(your_target_name PRIVATE cpr::cpr)

Tests

cpr provides a bunch of tests that can be executed via the following commands.

git clone https://github.com/libcpr/cpr.git
cd cpr && mkdir build && cd build
cmake .. -DCPR_BUILD_TESTS=ON # There are other test related options like 'CPR_BUILD_TESTS_SSL' and 'CPR_BUILD_TESTS_PROXY'
cmake --build . --parallel
ctest -VV # -VV is optional since it enables verbose output

Bazel

Please refer to hedronvision/bazel-make-cc-https-easy.

Packages for Linux Distributions

Alternatively, you may install a package specific to your Linux distribution. Since so few distributions currently have a package for cpr, most users will not be able to run your program with this approach.

Currently, we are aware of packages for the following distributions:

If there's no package for your distribution, try making one! If you do, and it is added to your distribution's repositories, please submit a pull request to add it to the list above. However, please only do this if you plan to actively maintain the package.

NuGet Package

For Windows, there is also a libcpr NuGet package available. Currently, x86 and x64 builds are supported with release and debug configuration.

The package can be found here: NuGet.org

Port for macOS

On macOS you may install cpr via MacPorts.org (arm64, x86_64, powerpc)

Requirements

The only explicit requirements are:

  • a C++17 compatible compiler such as Clang or GCC. The minimum required version of GCC is unknown, so if anyone has trouble building this library with a specific version of GCC, do let us know
  • in case you only have a C++11 compatible compiler available, all versions below cpr 1.9.x are for you. The 1.10.0 release of cpr switches to C++17 as a requirement.
  • If you would like to perform https requests OpenSSL and its development libraries are required.

Building cpr - Using vcpkg

You can download and install cpr using the vcpkg dependency manager:

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install cpr

The cpr port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Building cpr - Using Conan

You can download and install cpr using the Conan package manager. Setup your CMakeLists.txt (see Conan documentation on how to use MSBuild, Meson and others). An example can be found here.

The cpr package in Conan is kept up to date by Conan contributors. If the version is out of date, please create an issue or pull request on the conan-center-index repository.