Passa al contenuto principale

D01 - Esempio

esempio pratico e funzionante di programma in C che espone una API HTTP REST (es. /hello) usando una libreria leggera e molto usata: libmicrohttpd.

È ideale per:

  • servizi REST semplici

  • API interne di sistema

  • embedded / IoT

  • interfaccia con script o sistemi esterni

🚀 Esempio completo: API in C (GET /hello)

📌 Requisiti

Installa la libreria:

sudo apt-get install libmicrohttpd-dev

📄 api_server.c

#include <microhttpd.h>
#include <string.h>
#include <stdlib.h>

#define PORT 8080

// Funzione che gestisce le richieste HTTP
static int answer_to_connection(
    void *cls,
    struct MHD_Connection *connection,
    const char *url,
    const char *method,
    const char *version,
    const char *upload_data,
    size_t *upload_data_size,
    void **con_cls)
{
    const char *response_msg;

    if (strcmp(url, "/hello") == 0 && strcmp(method, "GET") == 0) {
        response_msg = "{\"message\": \"Hello from API in C!\"}";
    }
    else {
        response_msg = "{\"error\": \"Endpoint not found\"}";
    }

    struct MHD_Response *response;
    int ret;

    response = MHD_create_response_from_buffer(
        strlen(response_msg),
        (void*) response_msg,
        MHD_RESPMEM_PERSISTENT);

    MHD_add_response_header(response, "Content-Type", "application/json");
    ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
    MHD_destroy_response(response);

    return ret;
}

int main() {
    struct MHD_Daemon *daemon;

    daemon = MHD_start_daemon(
        MHD_USE_INTERNAL_POLLING_THREAD, PORT, NULL, NULL,
        &answer_to_connection, NULL, MHD_OPTION_END);

    if (daemon == NULL) {
        fprintf(stderr, "Error starting server\n");
        return 1;
    }

    printf("Server running on port %d\n", PORT);
    printf("Try: curl http://localhost:%d/hello\n", PORT);

    getchar();  // Ferma il server quando premi INVIO

    MHD_stop_daemon(daemon);
    return 0;
}


 

🔧 Compilazione

gcc api_server.c -o api_server -lmicrohttpd

▶️ Esecuzione

./api_server

🧪 Test con curl

curl http://localhost:8080/hello

Output:

{"message": "Hello from API in C!"}