Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

so-keyldzn/c-full-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

API REST en C

Une API REST haute performance développée en langage C, offrant une alternative rapide et efficace aux APIs traditionnelles.

🚀 Caractéristiques

  • Performance élevée : Latence < 10ms, throughput > 50,000 RPS
  • Consommation mémoire optimisée : < 50MB au démarrage
  • Support SSL/TLS : Chiffrement des communications
  • Base de données : SQLite, PostgreSQL, MySQL
  • Authentification : JWT, OAuth2, API Keys
  • Middleware modulaire : CORS, Rate limiting, Logging
  • Thread pool : Gestion optimisée des connexions
  • Cache intégré : Cache en mémoire configurable

📋 Prérequis

Système d'exploitation

  • Linux (Ubuntu 18.04+, CentOS 7+)
  • macOS (10.14+)
  • Windows (WSL2 recommandé)

Dépendances

  • GCC 7+ ou Clang 8+
  • CMake 3.12+
  • libmicrohttpd
  • libcjson
  • OpenSSL
  • SQLite3
  • PostgreSQL (optionnel)
  • UUID library

🛠️ Installation

Installation automatique des dépendances

# Ubuntu/Debian
make deps

# Ou manuellement
sudo apt-get update
sudo apt-get install -y build-essential cmake pkg-config \
    libmicrohttpd-dev libcjson-dev libssl-dev libsqlite3-dev \
    libpq-dev uuid-dev valgrind clang-format doxygen

Compilation

# Configuration et compilation
make setup
make build

# Ou avec CMake directement
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make -j$(nproc)

🚀 Utilisation

Interface Web Frontend

Pour tester l'API de manière visuelle, utilisez l'interface web intégrée :

# Démarrer l'interface web et tous les services
./scripts/start-frontend.sh

Puis ouvrez votre navigateur à : http://localhost:3001

L'interface web offre :

  • 🔐 Authentification JWT interactive
  • 📊 Test de tous les endpoints
  • 📱 Interface responsive moderne
  • 📋 Formatage automatique des réponses JSON
  • 📈 Monitoring en temps réel de l'API

Démarrage rapide (ligne de commande)

# Exécuter l'API
make run

# Ou directement
./build/api

# Avec options
./build/api --port 8080 --config config/production.json

Configuration

La configuration se fait via des fichiers JSON :

{
  "server": {
    "host": "127.0.0.1",
    "port": 8080,
    "max_connections": 1000,
    "thread_pool_size": 4
  },
  "database": {
    "type": "sqlite",
    "database": "data/api.db",
    "pool_size": 5
  },
  "security": {
    "jwt_secret": "your-secret-key",
    "jwt_expiration": 3600,
    "rate_limit": {
      "requests_per_minute": 60
    }
  }
}

Endpoints disponibles

GET    /api/v1/health          - Health check
GET    /api/v1/users           - Liste des utilisateurs
POST   /api/v1/users           - Créer un utilisateur
GET    /api/v1/users/{id}      - Récupérer un utilisateur
PUT    /api/v1/users/{id}      - Mettre à jour un utilisateur
DELETE /api/v1/users/{id}      - Supprimer un utilisateur
POST   /api/v1/auth/login      - Authentification
POST   /api/v1/auth/refresh    - Rafraîchir le token

Exemples d'utilisation

# Health check
curl http://localhost:8080/api/v1/health

# Créer un utilisateur
curl -X POST http://localhost:8080/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{"name": "John Doe", "email": "john@example.com"}'

# Authentification
curl -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "john@example.com", "password": "password123"}'

🧪 Tests

# Exécuter tous les tests
make test

# Tests unitaires
./build/tests/unit_tests

# Tests d'intégration
./build/tests/integration_tests

# Tests de performance
make perf

🔧 Développement

Structure du projet

api/
├── src/                    # Code source
│   ├── controllers/        # Contrôleurs REST
│   ├── models/            # Modèles de données
│   ├── middleware/        # Middleware
│   ├── utils/             # Utilitaires
│   ├── database/          # Accès base de données
│   ├── http/              # Serveur HTTP
│   └── main.c             # Point d'entrée
├── include/               # Headers
├── tests/                 # Tests
├── config/                # Configuration
├── docs/                  # Documentation
└── scripts/               # Scripts utilitaires

Compilation en mode debug

# Compilation debug
make debug

# Avec Valgrind
make profile

# Formatage du code
make format

# Analyse statique
make lint

Ajout de nouvelles fonctionnalités

  1. Nouveau contrôleur :

    // src/controllers/my_controller.c
    #include "controllers/my_controller.h"
    
    int my_controller_handler(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) {
        // Implémentation
    }
  2. Nouveau modèle :

    // include/models/my_model.h
    typedef struct {
        int id;
        char name[256];
        time_t created_at;
    } my_model_t;
  3. Nouveau middleware :

    // src/middleware/my_middleware.c
    int my_middleware(http_request_t *request, http_response_t *response) {
        // Traitement
        return MIDDLEWARE_CONTINUE;
    }

📊 Performance

Benchmarks

# Test de charge avec wrk
wrk -t12 -c400 -d30s http://localhost:8080/api/v1/health

# Test avec Apache Bench
ab -n 10000 -c 100 http://localhost:8080/api/v1/health

Métriques typiques

  • Latence : ~2ms (P50), ~5ms (P95), ~10ms (P99)
  • Throughput : 50,000+ RPS sur machine moderne
  • Mémoire : 30-50MB selon la configuration
  • CPU : Utilisation optimisée multi-thread

🐳 Docker

Avec Interface Web (Recommandé)

# Démarrer tous les services avec interface web
./scripts/start-frontend.sh

# Services disponibles :
# - Interface Web : http://localhost:3001
# - API REST      : http://localhost:8080
# - Grafana       : http://localhost:3000
# - Prometheus    : http://localhost:9090

API Seule

# Construire l'image
make docker-build

# Exécuter avec Docker
make docker-run

# Ou manuellement
docker build -t api-c .
docker run -p 8080:8080 -v $(pwd)/config:/app/config api-c

📚 Documentation

# Générer la documentation
make docs

# Ouvrir la documentation
open docs/html/index.html

🔒 Sécurité

Authentification JWT

// Exemple d'utilisation
char *token = jwt_create_token(user_id, expiration);
bool valid = jwt_verify_token(token);

Rate Limiting

{
  "security": {
    "rate_limit": {
      "requests_per_minute": 60,
      "burst_size": 10
    }
  }
}

CORS

{
  "security": {
    "cors": {
      "enabled": true,
      "origins": ["http://localhost:3000", "https://myapp.com"],
      "methods": ["GET", "POST", "PUT", "DELETE"],
      "headers": ["Content-Type", "Authorization"]
    }
  }
}

🚀 Déploiement

Systemd Service

# /etc/systemd/system/api-c.service
[Unit]
Description=API C Service
After=network.target

[Service]
Type=simple
User=api
WorkingDirectory=/opt/api-c
ExecStart=/opt/api-c/bin/api --config /opt/api-c/config/production.json
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

Nginx Reverse Proxy

server {
    listen 80;
    server_name api.example.com;
    
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

🤝 Contribution

  1. Fork le projet
  2. Créer une branche feature (git checkout -b feature/amazing-feature)
  3. Commit les changements (git commit -m 'Add amazing feature')
  4. Push vers la branche (git push origin feature/amazing-feature)
  5. Ouvrir une Pull Request

📄 Licence

Ce projet est sous licence MIT. Voir le fichier LICENSE pour plus de détails.

🆘 Support

🏆 Benchmarks

Métrique Valeur
Latence moyenne 2ms
Throughput 50,000+ RPS
Mémoire 30-50MB
Connexions simultanées 10,000+

📈 Roadmap

  • Support HTTP/2
  • Clustering multi-processus
  • Métriques Prometheus
  • Support WebSocket
  • Cache distribué Redis
  • Monitoring intégré

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors