Trabajo con redes y API HTTP en C++: guía detallada
What is it and why? (a real-life analogy)
Imagine you are sitting in a cozy cafe and want to order a pizza. You don't go to the kitchen yourself, don't climb into the oven, and don't touch the dough. Instead, you call the waiter, tell him: "Please bring a Margherita pizza," and after a while you get the finished dish.
Working with the network and HTTP API in programming is exactly the same. Your program is the cafe visitor. The server on the internet is the restaurant kitchen. And the HTTP API is the waiter who takes the order and brings the result.
When your program wants to get data from the internet (for example, weather, exchange rates, or a list of movies), it doesn't directly access the server's database. Instead, it sends an HTTP request to a specific address (URL), and the server returns an HTTP response with the required information.
💡 Important note: HTTP API (Application Programming Interface) is a set of rules by which programs communicate with each other over the internet. It's like a menu in a restaurant: you can only order what is written on the menu, and exactly as it is specified there.
Why is this needed? Modern programs rarely work in isolation. They exchange data with other services: get exchange rates, send messages, upload images, authenticate users. Without the ability to work with the network, your program will be like an island in the ocean — useful, but cut off from the world.
Theory: how it works from the inside
Let's look under the hood and understand what happens when your program sends an HTTP request.
What is HTTP?
HTTP (HyperText Transfer Protocol) is a data transfer protocol. Imagine it's the language that programs on the internet speak. Just as people agree to speak Russian or English, programs agree to speak HTTP.
Structure of an HTTP request
Each request consists of several parts:
- Method (verb) — what we want to do. The most popular ones: GET (retrieve), POST (create), PUT (update), DELETE (delete).
- URL (address) — where we are addressing. For example:
https://api.weather.com/v1/current?city=Moscow - Headers — additional information: who we are, what data format we accept, whether we have an access key.
- Body — the data we send (usually in POST or PUT requests).
Structure of an HTTP response
The server responds in a similar way:
- Status code — a number that indicates whether everything is fine. 200 — great, 404 — not found, 500 — server error.
- Headers — service information from the server.
- Body — the actual data (usually in JSON or XML format).
What does this look like in reality?
When you open a website in your browser, the browser sends a GET request to the server. The server processes it and returns an HTML page. In the case of an API, the server returns not a page, but raw data that your program can process.
🔍 Important: C++ does not have built-in support for HTTP requests (unlike Python). We will need special libraries. The most popular one is cURL (libcurl). It is available almost everywhere and works on Windows, Linux, and macOS.
Syntax in C++: all forms and variants
In C++, to work with the HTTP API, we will use the libcurl library. It is a powerful and time-tested library that supports all possible protocols and methods.
Installing libcurl
Before writing code, you need to install the library:
- Windows (vcpkg):
vcpkg install curl - Linux (apt):
sudo apt-get install libcurl4-openssl-dev - macOS (brew):
brew install curl
Basic libcurl functions
| Function | Description |
|---|---|
curl_easy_init() |
Creates a new HTTP session |
curl_easy_setopt() |
Configures request parameters (URL, method, headers) |
curl_easy_perform() |
Performs the request |
curl_easy_cleanup() |
Frees memory after completion |
curl_slist_append() |
Adds headers to the request |
Request types (methods)
| Method | Purpose | Configuration in libcurl |
|---|---|---|
| GET | Retrieve data | Default (no changes needed) |
| POST | Send data to the server | curl_easy_setopt(curl, CURLOPT_POST, 1L); |
| PUT | Update existing data | curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); |
| DELETE | Delete data | curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); |
Code examples — from simple to complex
Now let's move on to the most interesting part — the code. All examples are functional and can be copied and run.
Example 1: Simple GET request (retrieving data)
// Include libraries
#include <iostream>
#include <string>
#include <curl/curl.h>
// Helper function: writes the server response to a string
size_t writeCallback(void* contents, size_t size, size_t nmemb, std::string* output) {
size_t totalSize = size * nmemb;
output->a