Creating a RESTful API in C is a bit unconventional compared to modern languages like Python or JavaScript, but it’s a great way to dive deep into the mechanics of web servers and APIs. This post will guide you through implementing a simple airline API in GNU C on an Arch Linux host and show you how to query this API using C#.

Prerequisites

Before we begin, ensure you have the following installed on your Arch Linux system:

  • GCC (GNU Compiler Collection)
  • libmicrohttpd (for handling HTTP requests)
  • json-c (for JSON handling)
  • Mono (for running C# code on Linux)

You can install these via pacman:

sudo pacman -S gcc libmicrohttpd json-c mono

Step 1: Setting Up the Airline API in C

We’ll use libmicrohttpd for handling HTTP requests and json-c for JSON parsing and generation.

1.1. Install Required Libraries

Ensure libmicrohttpd and json-c are installed:

sudo pacman -S libmicrohttpd json-c

1.2. Create the Airline API

Create a new directory for your project and navigate into it:

mkdir airline_api
cd airline_api

Create a file named airline_api.c:

#include <microhttpd.h>
#include <json-c/json.h>
#include <stdio.h>
#include <string.h>

#define PORT 8888

struct Airline {
    int id;
    const char *name;
    const char *destination;
};

struct Airline airlines[] = {
    {1, "Airline A", "New York"},
    {2, "Airline B", "Los Angeles"},
    {3, "Airline C", "Chicago"}
};

static int send_response(struct MHD_Connection *connection, const char *json) {
    struct MHD_Response *response;
    int ret;

    response = MHD_create_response_from_buffer(strlen(json), (void *) json, MHD_RESPMEM_PERSISTENT);
    if (!response) return MHD_NO;

    MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, "application/json");
    ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
    MHD_destroy_response(response);
    return ret;
}

static int request_handler(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) {
    struct json_object *json = json_object_new_array();

    for (int i = 0; i < sizeof(airlines) / sizeof(airlines[0]); i++) {
        struct json_object *airline_obj = json_object_new_object();
        json_object_object_add(airline_obj, "id", json_object_new_int(airlines[i].id));
        json_object_object_add(airline_obj, "name", json_object_new_string(airlines[i].name));
        json_object_object_add(airline_obj, "destination", json_object_new_string(airlines[i].destination));
        json_object_array_add(json, airline_obj);
    }

    const char *json_str = json_object_to_json_string(json);
    int ret = send_response(connection, json_str);
    json_object_put(json);
    return ret;
}

int main() {
    struct MHD_Daemon *daemon;

    daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, PORT, NULL, NULL, &request_handler, NULL, MHD_OPTION_END);
    if (!daemon) return 1;

    printf("Server is running on port %d\n", PORT);
    getchar(); // Wait for user input to stop the server

    MHD_stop_daemon(daemon);
    return 0;
}

1.3. Compile the Airline API

Compile the C program:

gcc -o airline_api airline_api.c -lmicrohttpd -ljson-c

1.4. Run the Airline API

Run the compiled program:

./airline_api

Your API should now be running on http://localhost:8888.

Step 2: Querying the API with C

Next, let’s create a C# program to query our airline API.

2.1. Create a New C# Project

Create a new directory for your C# project and navigate into it:

mkdir airline_client
cd airline_client

Create a file named Program.cs:

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

class Program
{
    static async Task Main(string[] args)
    {
        string url = "http://localhost:8888";

        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();

            JArray airlines = JArray.Parse(responseBody);
            foreach (var airline in airlines)
            {
                Console.WriteLine($"ID: {airline["id"]}, Name: {airline["name"]}, Destination: {airline["destination"]}");
            }
        }
    }
}

2.2. Install Required Libraries

Install the Newtonsoft.Json package for JSON handling:

dotnet new console -n AirlineClient
cd AirlineClient
dotnet add package Newtonsoft.Json

2.3. Compile and Run the C# Program

Compile the C# program:

dotnet build

Run the compiled program:

dotnet run

Summary

In this tutorial, we created a simple RESTful API using GNU C and libmicrohttpd on Arch Linux. We defined an endpoint that returns a list of airlines in JSON format. We then created a C# client application that queries this API and displays the airline information.

This exercise not only demonstrates the power and flexibility of C for creating web servers but also showcases the interoperability between different programming environments. By leveraging libraries like libmicrohttpd and json-c in C, and using modern C# features and libraries, we can build robust and efficient applications across platforms.

Building a RESTful Airline API in GNU C on Arch Linux

Johannes Rest


.NET Architekt und Entwickler


Beitragsnavigation


Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert