Home Wiki Programming & Logic API Integration: Digitally Connecting the Factory
Programming & Logic

API Integration: Digitally Connecting the Factory

What is an API?

An Application Programming Interface (API) is a set of rules that defines how one program requests services from another. In industrial settings, APIs connect systems that were never designed to talk to each other: SCADA reads sensors, ERP manages inventory, and a cloud dashboard shows reports to management. APIs are the bridges between all of them.

Industrial APIs commonly connect:

  • SCADA systems to cloud databases
  • ERP platforms to production lines
  • IoT sensors to analytics platforms
  • Mobile apps to monitoring dashboards

HTTP: The Foundation of Web Communication

Every web API request uses HTTP (HyperText Transfer Protocol). Each request consists of:

  1. Method: what you want to do
  2. URL: where to reach
  3. Headers: metadata (content type, authentication)
  4. Body: data payload (for POST and PUT)

Core HTTP Methods

Method Purpose Industrial Example
GET Read data Fetch a temperature sensor reading
POST Create a resource Log a new alarm event
PUT Replace a resource Update machine configuration
PATCH Partial update Change a single alarm threshold
DELETE Remove a resource Remove an outdated maintenance schedule

Status Codes

2xx = Success:      200 OK, 201 Created
3xx = Redirection:  301 Moved, 304 Not Modified
4xx = Client Error: 400 Bad Request, 401 Unauthorized, 404 Not Found
5xx = Server Error: 500 Internal Error, 503 Service Unavailable

What is REST?

REST (Representational State Transfer) is an architectural style -- a set of constraints that make APIs simple, scalable, and predictable:

  1. Stateless: each request contains all information needed -- the server does not remember previous requests
  2. Resources: everything is represented as a resource with a unique URL
  3. Representations: resources are sent as JSON or XML
  4. Uniform Interface: standard HTTP methods are used consistently

Example -- a factory machine management API:

GET    /api/machines          -> List all machines
GET    /api/machines/42       -> Get machine 42 details
POST   /api/machines          -> Add a new machine
PUT    /api/machines/42       -> Update machine 42
DELETE /api/machines/42       -> Remove machine 42
GET    /api/machines/42/alarms -> Get alarms for machine 42

JSON: The Data Language

JSON (JavaScript Object Notation) is the most widely used data format in modern APIs. It is human-readable, lightweight, and language-agnostic.

{
  "machine_id": 42,
  "name": "CNC Lathe - Haas ST-20",
  "location": "Hall B, Line 3",
  "status": "running",
  "temperature_c": 67.5,
  "spindle_rpm": 2400,
  "alarms": [],
  "last_maintenance": "2025-12-15",
  "sensors": {
    "vibration_mm_s": 3.2,
    "oil_pressure_bar": 4.8,
    "power_kw": 12.7
  }
}

JSON data types:

  • String: "running" -- enclosed in double quotes
  • Number: 67.5 -- no quotes
  • Boolean: true or false
  • Array: [1, 2, 3] -- ordered list
  • Object: {"key": "value"} -- key-value pairs
  • Null: null

WebSocket: Live Connections

HTTP follows a request-response pattern: the client asks, the server answers, and the connection closes. But industrial monitoring needs continuous real-time data -- sensor readings every second, instant alarms, live machine status.

WebSocket opens a persistent, bidirectional channel between client and server.

Traditional HTTP:
  Client -> "Give me temperature" -> Server
  Client <- "67.5C" <- Server
  (connection closes)
  Client -> "Give me temperature" -> Server
  Client <- "68.1C" <- Server
  (connection closes)

WebSocket:
  Client <-> Server (persistent connection)
  <- "67.5C"
  <- "68.1C"
  <- "WARNING: Temperature high!"
  -> "Stop the machine"

Practical Example: Sensor Monitoring via WebSocket

// Connect to the WebSocket server for production line monitoring
const ws = new WebSocket('ws://192.168.1.100:8080/live');

ws.onopen = () => {
  console.log('Connected to monitoring server');
  // Subscribe to machine 42 sensor data
  ws.send(JSON.stringify({
    action: 'subscribe',
    machine_id: 42,
    sensors: ['temperature', 'vibration', 'power']
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  // data = { machine_id: 42, temperature_c: 68.1, vibration_mm_s: 3.5, ... }

  if (data.temperature_c > 85) {
    triggerAlarm('High temperature on machine ' + data.machine_id);
  }
  updateDashboard(data);
};

ws.onerror = (error) => {
  console.error('Connection error:', error);
};

Authentication and Security

Securing industrial APIs is not optional. You do not want unauthorized users shutting down a production line with a single API call.

API Key

The simplest approach -- a unique key sent with every request:

GET /api/machines HTTP/1.1
Host: factory.local
X-API-Key: sk_prod_a1b2c3d4e5f6

Bearer Token (JWT)

The most common approach -- the user logs in and receives a temporary token:

POST /api/auth/login
Body: { "username": "operator1", "password": "..." }
Response: { "token": "eyJhbGciOiJIUzI1NiIs..." }

GET /api/machines
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

Critical Security Practices

  • Never send passwords in plain text -- always use HTTPS
  • Role-based access: operators read only, engineers read and write, admins control everything
  • Rate limiting: prevent flooding the server with excessive requests
  • Log every request: who did what, and when

Integration Example: SCADA to API to Dashboard

A complete real-world scenario:

+--------------+      +---------------+      +--------------+
|    SCADA     |      |  API Server   |      |  Dashboard   |
|   (Modbus)   |----->|   (REST +     |<---->|   (React)    |
|              |      |  WebSocket)   |      |              |
+--------------+      +---------------+      +--------------+
                            |
                      +-----+------+
                      |  Database  |
                      |(TimeSeries)|
                      +------------+

Step 1: SCADA reads sensors via Modbus and posts to the API every 5 seconds:

import requests
import time

SCADA_API = "http://factory-server:3000/api/readings"
API_KEY = "sk_prod_a1b2c3d4"

while True:
    reading = {
        "machine_id": 42,
        "timestamp": "2025-12-20T14:30:00Z",
        "temperature_c": read_modbus_register(40001),
        "pressure_bar": read_modbus_register(40002),
        "vibration_mm_s": read_modbus_register(40003)
    }
    response = requests.post(
        SCADA_API,
        json=reading,
        headers={"X-API-Key": API_KEY}
    )
    if response.status_code == 201:
        print("Reading recorded successfully")
    time.sleep(5)

Step 2: The dashboard receives data in real time via WebSocket and renders live charts.

API Testing Tools

Always test your API before connecting systems:

  • curl: simple command-line tool available on every OS
  • Postman: graphical interface for building and testing requests
  • HTTPie: elegant curl alternative with automatic syntax highlighting
# Fetch the list of machines using curl
curl -H "X-API-Key: sk_prod_a1b2c3" \
     http://factory-server:3000/api/machines

# Post a new reading
curl -X POST http://factory-server:3000/api/readings \
     -H "Content-Type: application/json" \
     -H "X-API-Key: sk_prod_a1b2c3" \
     -d '{"machine_id": 42, "temperature_c": 67.5}'

Summary

Technology When to Use Example
REST API CRUD operations, system integration Connect ERP with production line
WebSocket Real-time data, live monitoring Machine monitoring dashboard
JSON Structured data exchange Send sensor readings
HTTP Methods Define operation type GET to read, POST to create

APIs are the backbone of any smart factory. Mastering them means being able to connect any system to any other system -- and that is the essence of Industry 4.0.

API REST WebSocket JSON HTTP integration واجهة البرمجة التكامل الربط البرمجي بروتوكول HTTP البيانات المهيكلة الاتصال بالسحابة