DEV Community

Cover image for Dive into APIs: REST, SOAP, GraphQL & WebSocket
Gazi Nahian
Gazi Nahian

Posted on

Dive into APIs: REST, SOAP, GraphQL & WebSocket

APIs are the magic bridges connecting apps and data! But which one should you use? Let's break it down with code examples that’ll make you go, “Oh, that’s cool!” 😃


1️⃣ REST API – The Classic

A widely used web API architecture that operates over HTTP and uses URLs for resource identification. It primarily relies on standard HTTP methods like GET, POST, PUT, DELETE.

📝 Quick REST API (Node.js & Express)

const express = require('express');
const app = express();
const books = [{ id: 1, title: "\"JavaScript Magic\" }];"

app.get('/books', (req, res) => res.json(books));
app.listen(8080, () => console.log('📡 REST API running on port 8080!'));

Enter fullscreen mode Exit fullscreen mode

2️⃣ SOAP API – Old but Gold 💎

SOAP is a protocol for exchanging structured information, often used in enterprise applications. It uses XML for messages and enforces a strict structure, making it secure and reliable.

📝 Sample SOAP Request

<soapenv:Envelope>
  <soapenv:Body>
    <GetBook>
      <ID>1</ID>
    </GetBook>
  </soapenv:Body>
</soapenv:Envelope>

Enter fullscreen mode Exit fullscreen mode

3️⃣ GraphQL – The Customizer 🛠️

A query language for APIs that allows clients to request specific data, avoiding over-fetching. Clients define the structure of the response, making it flexible and efficient.

📝 Query Example

{
  book(id: "1") {
    title
    author
  }
}

Enter fullscreen mode Exit fullscreen mode

📝 Tiny GraphQL API (Node.js)

const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type Book { id: ID, title: String }
  type Query { books: [Book] }
`;

const resolvers = {
  Query: { books: () => [{ id: 1, title: "JavaScript Magic" }] }
};

new ApolloServer({ typeDefs, resolvers }).listen(4000, () =>
  console.log("⚡ GraphQL API running on port 4000!")
);

Enter fullscreen mode Exit fullscreen mode

4️⃣ WebSocket – Real-time Magic! 🎩✨

Enables real-time, two-way communication between the client and server over a persistent connection. Commonly used in chat apps, gaming, and live notifications.

📝 WebSocket Server (Node.js)

const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });

server.on('connection', socket => {
  socket.send('🎉 Welcome to WebSocket!');
});

Enter fullscreen mode Exit fullscreen mode

📝 WebSocket Client

const socket = new WebSocket("ws://localhost:8080");
socket.onmessage = event => console.log("📩 Message received:", event.data);

Enter fullscreen mode Exit fullscreen mode

🎯 Final Thoughts

Each API has its superpowers:

  • REST – Simple & scalable 🏗️
  • SOAP – Secure & reliable 🔒
  • GraphQL – Flexible & efficient 🎛️
  • WebSocket – Real-time & interactive ⚡

Choose the right tool for the job! 🔥

Top comments (0)