AlexDev

Join the Gang Gang and have the latest AI and Tech content.

Home page View on GitHub

api.h

Posted on 9 October 2023.
c linux

About

API.h is a simple header-only library for creating an HTTP API. It attempts to be a blazingly fast alternative to libraries such as express.

QuickStart

This is a C library, written with simplicty in mind. You will need to just copy paste the file into your project, include it and then use the functions.

wget https://raw.githubusercontent.com/alexjercan/api.h/master/api.h

To be able to use the library include it into your project and define the implementation.

#define API_IMPLEMENTATION
#include "api.h"

Create a new router.

struct API_Router *router = api_create();

Add a callback to the / path

api_route(router, "/", METHOD_GET, *callback);

Start listening on port 8000 on 0.0.0.0

api_start(router, "0.0.0.0", 8000);

Define the callback

API_Response callback(API_Request request) {
    API_Response response = { .status = 200, .body = "Hello World" };

    return response;
}

Build the application

clang main.c api.h -o main

Start the server

./main

You can now make a curl request

curl localhost:8000/

You should get a Hello World message!

Docs

Structures

Functions

Examples

In the examples folder you can see how to use the library.

cd examples
make
  1. Curl

Basic example, this will just respond with a string that contains a simple message for different routes.

In one terminal start the http server

./curl/main

Then you can try to make curl requests to it

curl localhost:8080/
curl localhost:8080/another
curl localhost:8080/notexist
  1. HTML

Simple example that reads an html file from disk and sends it’s contents as response.

In one terminal start the http server

./html/main

Then you can try to make curl requests to it or open it in browser

curl localhost:8080

Conclusion