DEV Community

Cover image for Top 8 API Architectural Styles Across Tech Industry (Part 2)
Engr SoluTion
Engr SoluTion

Posted on • Updated on

Top 8 API Architectural Styles Across Tech Industry (Part 2)

In this journey of exploring the leading API architectural styles in the programming domain, we'll pick up from where we left off in the previous segment. If you haven't had the chance to catch the previous episode, I recommend doing so for context before proceeding. This current episode seamlessly follows the narrative of its predecessor.

Without further ado, let's delve into the topic at hand.

5. WebSocket:

WebSocket provides full-duplex communication channels over a single TCP (Transmission Control Protocol) connection. It is suitable for real-time applications that require continuous data exchange between the client and the server, such as chat applications, notifications, and online gaming.

Implementation in Python

# python

import asyncio
import websockets

async def handle_client(websocket, path):
    async for message in websocket:
        await websocket.send(message)

start_server = websockets.serve(handle_client, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

Enter fullscreen mode Exit fullscreen mode

Implementation in JavaScript

// server.js

const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost:8765');

ws.on('open', () => {
  console.log('Connected to WebSocket server');
  ws.send('Hello from WebSocket Client!');
});

ws.on('message', (message) => {
  console.log(`Received: ${message}`);
});

Enter fullscreen mode Exit fullscreen mode

6. Webhook:

Webhooks are a way for one application to provide real-time data to another application by sending HTTP requests when a certain event occurs. They are commonly used to integrate services, allowing one service to automatically notify another when specific events happen.
Note: It is an event-driven kind of architecture.

Implementation in Python

# python

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    event_data = request.json  # Received event data from the webhook
    print('Received event:', event_data)

    # Process the event data here

    return jsonify({'message': 'Webhook received successfully'})

if __name__ == '__main__':
    app.run(debug=True)

Enter fullscreen mode Exit fullscreen mode

Implementation in JavaScript

// server.js

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

app.use(bodyParser.json());

app.post('/webhook', (req, res) => {
    const eventData = req.body; // Received event data from the webhook
    console.log('Received event:', eventData);

    // Process the event data here

    res.status(200).send('Webhook received successfully');
});

app.listen(port, () => {
    console.log(`Webhook server is running on port ${port}`);
});


Enter fullscreen mode Exit fullscreen mode

7. Message Queuing Telemetry Transport (MQTT):

MQTT is a lightweight messaging protocol designed for efficient communication between devices and applications in scenarios where bandwidth and resources are limited. It follows a publish-subscribe model, where devices (publishers) send messages to topics, and other devices or applications (subscribers) receive messages from subscribed topics.

Implementation in Python

# python

# MQTT Publisher in Python:
import paho.mqtt.client as mqtt

client = mqtt.Client()
client.connect('localhost', 1883)  # Replace with your broker address

topic = 'temperature'
message = '25°C'

client.publish(topic, message)
print(f"Published to topic '{topic}': {message}")

client.disconnect()


---


# MQTT Subscriber in Python:
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    client.subscribe('temperature')

def on_message(client, userdata, msg):
    print(f"Received from topic '{msg.topic}': {msg.payload.decode()}")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect('localhost', 1883)  # Replace with your broker address
client.loop_forever()

Enter fullscreen mode Exit fullscreen mode

Implementation in JavaScript

// server.js

const mqtt = require('mqtt');

const client = mqtt.connect('mqtt://localhost:1883'); // Replace with your broker URL

client.on('connect', () => {
    const topic = 'temperature';
    const message = '25°C';

    client.publish(topic, message);
    console.log(`Published to topic '${topic}': ${message}`);

    client.end();
});

Enter fullscreen mode Exit fullscreen mode

8. Advanced Message Queuing Protocol (AMQP):

AMQP is an open standard messaging protocol that enables communication between different applications or components in a distributed system. It provides reliable, secure, and interoperable messaging capabilities. AMQP supports various messaging patterns, including point-to-point, publish-subscribe, and request-response.

Implementation in Python

# python

# AMQP Publisher in Python:

import pika

# Replace with your AMQP broker address
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) 
channel = connection.channel()

exchange_name = 'logs'
message = 'Hello, AMQP!'

channel.exchange_declare(exchange=exchange_name, exchange_type='fanout')
channel.basic_publish(exchange=exchange_name, routing_key='', body=message)

print(f"Published to exchange '{exchange_name}': {message}")

connection.close()


---


# AMQP Subscriber in Python:

import pika

# Replace with your AMQP broker address
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) 
channel = connection.channel()

exchange_name = 'logs'

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue

channel.exchange_declare(exchange=exchange_name, exchange_type='fanout')
channel.queue_bind(exchange=exchange_name, queue=queue_name)

print(f"Waiting for messages in queue '{queue_name}'")

def callback(ch, method, properties, body):
    print(f"Received: {body}")

channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
channel.start_consuming()


Enter fullscreen mode Exit fullscreen mode

Implementation in JavaScript

// server.js

# AMQP Publisher in JavaScript (Node.js):

const amqp = require('amqplib');

async function publishMessage() {
    // Replace with your AMQP broker URL
    const connection = await amqp.connect('amqp://localhost'); 
    const channel = await connection.createChannel();

    const exchangeName = 'logs';
    const message = 'Hello, AMQP!';

    await channel.assertExchange(exchangeName, 'fanout', { durable: false });
    channel.publish(exchangeName, '', Buffer.from(message));

    console.log(`Published to exchange '${exchangeName}': ${message}`);

    await channel.close();
    await connection.close();
}

publishMessage();


---


# AMQP Subscriber in JavaScript (Node.js):

const amqp = require('amqplib');

async function subscribeToMessages() {
    // Replace with your AMQP broker URL
    const connection = await amqp.connect('amqp://localhost'); 
    const channel = await connection.createChannel();

    const exchangeName = 'logs';

    await channel.assertExchange(exchangeName, 'fanout', { durable: false });
    const q = await channel.assertQueue('', { exclusive: true });
    channel.bindQueue(q.queue, exchangeName, '');

    console.log(`Waiting for messages in queue '${q.queue}'`);

    channel.consume(q.queue, (msg) => {
        console.log(`Received: ${msg.content.toString()}`);
    }, { noAck: true });
}

subscribeToMessages();

Enter fullscreen mode Exit fullscreen mode

What an incredible journey it has been! I hope you've gained a wealth of knowledge from this article. 😊

Share in the comments what you've discovered so far and your insights on this post. Your thoughts mean a lot to me! Thank you for engaging by liking, commenting, and spreading the word.

To explore further content like this, don't hesitate to follow me on this platform and connect with me on my social accounts. Stay curious and keep learning! 🚀📚

You can check out the first part of this article Here 🔥🔥🔥


Connect with me 🔥🔥

GitHub
Twitter
LinkedIn
Instagram
Facebook Page

Till the next post, Stay tuned 😍

Top comments (0)