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!'));
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>
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
}
}
π 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!")
);
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!');
});
π WebSocket Client
const socket = new WebSocket("ws://localhost:8080");
socket.onmessage = event => console.log("π© Message received:", event.data);
π― 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)