REST API requests in C
Introduction
The C standard library has no HTTP client. But a REST API is a text
protocol over TCP, and C has TCP: POSIX sockets,
socket, connect,
send and recv. The request
is a string you build, the answer is a string you read.
That covers http://: a local service, a test
stand, an internal network. https:// needs TLS,
and C has none without a library: OpenSSL or libcurl. libcurl is a
library, not part of the language; a normal project makes REST calls with
it, and drops to sockets when the library cannot be added and the service
speaks plain http.
The same request in C++, with libcurl, RAII and
std::string, is on
the C++ REST page.
Below is a working program that sends a request and prints the whole
answer, and the output it gave against a local test server.
A test server
Without the internet the requests are checked against your own server. The simplest one is http.server from Python: it serves the files of the current directory and understands GET only.
python3 -m http.server 8000
The command holds the terminal, so the requests come from a second one. POST, PUT and DELETE need a handler that accepts them: the file server.py in the same directory answers with a code and sends the request body back.
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def answer(self, code, body=""):
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body.encode())
def do_GET(self):
self.answer(200, '{"status": "ok"}')
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
self.answer(201, '{"created": ' + body.decode() + '}')
def do_PUT(self):
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
self.answer(200, '{"replaced": ' + body.decode() + '}')
def do_DELETE(self):
self.answer(204)
HTTPServer(("127.0.0.1", 8001), Handler).serve_forever()
python3 server.py
GET
The order of calls is the same for every method:
getaddrinfo turns the address and the port into a
structure, socket creates the socket,
connect opens the connection,
send writes the request text and
recv reads the answer until the server closes the
connection.
The file rest.c:
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
if (argc < 3) {
fprintf(stderr, "usage: %s METHOD PATH [BODY]\n", argv[0]);
return 2;
}
const char *method = argv[1];
const char *path = argv[2];
const char *body = (argc > 3) ? argv[3] : "";
struct addrinfo hints = {0};
struct addrinfo *res;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo("127.0.0.1", "8001", &hints, &res) != 0) {
perror("getaddrinfo");
return 1;
}
int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (fd < 0 || connect(fd, res->ai_addr, res->ai_addrlen) != 0) {
perror("connect");
return 1;
}
char request[1024];
snprintf(request, sizeof(request),
"%s %s HTTP/1.1\r\n"
"Host: 127.0.0.1:8001\r\n"
"Accept: application/json\r\n"
"Content-Type: application/json\r\n"
"Content-Length: %zu\r\n"
"Connection: close\r\n"
"\r\n"
"%s",
method, path, strlen(body), body);
send(fd, request, strlen(request), 0);
char answer[4096];
ssize_t got;
while ((got = recv(fd, answer, sizeof(answer) - 1, 0)) > 0) {
answer[got] = '\0';
fputs(answer, stdout);
}
close(fd);
freeaddrinfo(res);
return 0;
}
gcc -std=c17 -Wall -Wextra rest.c -o rest
A GET request:
./rest GET /index.txt
HTTP/1.0 200 OK Server: SimpleHTTP/0.6 Python/3.14.10 Date: Wed, 18 Nov 2026 07:02:26 GMT Content-type: text/plain Content-Length: 27 Last-Modified: Wed, 18 Nov 2026 07:02:15 GMT hello from the test server
The whole answer arrives: the status line, the headers, an empty line and the body. The program prints it as it is, because parsing JSON is a separate job; at this step what matters is that the request arrived and the server answered.
The status code
Success or refusal is in the first line of the answer. The number can be taken with sscanf:
int status = 0;
if (sscanf(answer, "HTTP/%*d.%*d %d", &status) == 1) {
printf("status: %d\n", status);
}
status: 404
A request for a missing file gives the same status line with another number:
./rest GET /nope.txt
HTTP/1.0 404 File not found Server: SimpleHTTP/0.6 Python/3.14.10 Date: Wed, 18 Nov 2026 07:02:58 GMT Connection: close Content-Type: text/html;charset=utf-8 Content-Length: 460
POST
The method is the first word of the request line. A POST has a body, so it needs Content-Length with the body length in bytes and Content-Type with its type; an access token goes as an ordinary header. The body fits into the same snprintf:
snprintf(request, sizeof(request),
"POST /rules HTTP/1.1\r\n"
"Host: 127.0.0.1:8001\r\n"
"Authorization: Bearer a-proper-token-goes-here\r\n"
"Content-Type: application/json\r\n"
"Content-Length: %zu\r\n"
"Connection: close\r\n"
"\r\n"
"%s",
strlen(body), body);
./rest POST /rules '{"name":"rule1"}'
HTTP/1.0 201 Created Server: BaseHTTP/0.6 Python/3.14.10 Date: Wed, 18 Nov 2026 07:02:51 GMT Content-Type: application/json Content-Length: 29 {"created": {"name":"rule1"}}
PUT
A PUT replaces the whole object, so the path carries its identifier and the body is a complete object, not a set of changes:
./rest PUT /rules/r_id '{"name":"rule2"}'
HTTP/1.0 200 OK Server: BaseHTTP/0.6 Python/3.14.10 Date: Wed, 18 Nov 2026 07:02:51 GMT Content-Type: application/json Content-Length: 30 {"replaced": {"name":"rule2"}}
DELETE
A DELETE has no body: the path names the resource and the token confirms the right to remove it.
./rest DELETE /rules/r_id
HTTP/1.0 204 No Content Server: BaseHTTP/0.6 Python/3.14.10 Date: Wed, 18 Nov 2026 07:02:51 GMT Content-Type: application/json Content-Length: 0
204 means it worked and the answer has no body. An unknown method is refused with 501, and that too is the server answering, not the program failing:
./rest PATCH /x
HTTP/1.0 501 Unsupported method ('PATCH')
What plain C does not have
A socket gives bytes. Everything else is written by hand or taken from a library:
- TLS. https:// needs a handshake and encryption; C has none of it without a library. OpenSSL adds TLS over a socket, libcurl does that plus HTTP.
- Answer parsing. Headers, chunked and Content-Length are an HTTP client already; here the answer is only printed.
- JSON. The body is a string; taking a field out of it needs a parser (cJSON, for one), not strstr.
- Repeated requests. This program opens one connection and closes it after the answer (Connection: close). A hundred requests need a connection pool or a library.
That is why production C takes libcurl: it does http and https, parses the answer and reuses connections. Sockets stay for the case where the library cannot be added and the service is your own and speaks http.
Every command and every answer on this page was produced with gcc 15.2.0 and Python 3.14.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container; the server ran on 127.0.0.1 and the internet was not used.
Article author: Arthur Isaev