1.. _http_client_interface:
2
3HTTP Client
4###########
5
6.. contents::
7    :local:
8    :depth: 2
9
10Overview
11********
12
13The HTTP client library allows you to send HTTP requests and
14parse HTTP responses. The library communicates over the sockets
15API but it does not create sockets on its own.
16It can be enabled with :kconfig:option:`CONFIG_HTTP_CLIENT` Kconfig option.
17
18The application must be responsible for creating a socket and passing it to the library.
19Therefore, depending on the application's needs, the library can communicate over
20either a plain TCP socket (HTTP) or a TLS socket (HTTPS).
21
22Sample Usage
23************
24
25The API of the HTTP client library has a single function.
26
27The following is an example of a request structure created correctly:
28
29.. code-block:: c
30
31    struct http_request req = { 0 };
32    static uint8_t recv_buf[512];
33
34    req.method = HTTP_GET;
35    req.url = "/";
36    req.host = "localhost";
37    req.protocol = "HTTP/1.1";
38    req.response = response_cb;
39    req.recv_buf = recv_buf;
40    req.recv_buf_len = sizeof(recv_buf);
41
42    /* sock is a file descriptor referencing a socket that has been connected
43     * to the HTTP server.
44     */
45    ret = http_client_req(sock, &req, 5000, NULL);
46
47If the server responds to the request, the library provides the response to the
48application through the response callback registered in the request structure.
49As the library can provide the response in chunks, the application must be able
50to process these.
51
52Together with the structure containing the response data, the callback function
53also provides information about whether the library expects to receive more data.
54
55The following is an example of a very simple response handling function:
56
57.. code-block:: c
58
59    static void response_cb(struct http_response *rsp,
60                            enum http_final_call final_data,
61                            void *user_data)
62    {
63        if (final_data == HTTP_DATA_MORE) {
64            LOG_INF("Partial data received (%zd bytes)", rsp->data_len);
65        } else if (final_data == HTTP_DATA_FINAL) {
66            LOG_INF("All the data received (%zd bytes)", rsp->data_len);
67        }
68
69        LOG_INF("Response status %s", rsp->http_status);
70    }
71
72See :zephyr:code-sample:`HTTP client sample application <sockets-http-client>` for
73more information about the library usage.
74
75API Reference
76*************
77
78.. doxygengroup:: http_client
79