DEV Community

Cover image for Top 8 API Architectural Styles Across Tech Industry
Engr SoluTion
Engr SoluTion

Posted on • Updated on

Top 8 API Architectural Styles Across Tech Industry

In this post, I will delve into the prominent API architectural styles within the realm of programming that are worthy of discussion today, with some common implementation in Python and JavaScript.

First of all, What is an API?

API (Application Programming Interface) architectural styles define the way in which different components of software systems communicate and interact with each other.
There are several architectural styles for designing APIs, and here are eight major ones:

1. Remote Procedure Call (RPC):

RPC involves invoking procedures or functions on a remote server as if they were local. It abstracts the network communication and provides a way for clients to call methods on remote services. Examples of RPC APIs include gRPC and XML-RPC.

Implementation in Python

# main.py

import grpc
from rpc_example_pb2 import HelloRequest
from rpc_example_pb2_grpc import GreeterServicer, add_GreeterServicer_to_server

class Greeter(GreeterServicer):
    def SayHello(self, request, context):
        return HelloReply(message='Hello, ' + request.name)

server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()

Enter fullscreen mode Exit fullscreen mode

Implementation in JavaScript

// server.js

const { GreeterClient } = require('./rpc_example_pb_grpc.js');
const { HelloRequest } = require('./rpc_example_pb.js');

const client = new GreeterClient('http://localhost:8080');

const request = new HelloRequest();
request.setName('John');

client.sayHello(request, {}, (error, response) => {
    if (!error) {
        console.log('Greeting:', response.getMessage());
    }
}); 

Enter fullscreen mode Exit fullscreen mode

2. Representational State Transfer (REST):

REST is a widely and commonly used architectural style that is based on a set of constraints to build scalable and maintainable APIs. RESTful APIs use HTTP methods (GET, POST, PUT / PATCH, DELETE) to perform CRUD operations on resources represented by URLs. They rely on stateless communication and use standard status codes for response interpretation.

Implementation in Python

# main.py

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/hello', methods=['GET'])
def hello():
    return jsonify({'message': 'Hello, World!'})

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

Enter fullscreen mode Exit fullscreen mode

Implementation in JavaScript

// server.js

const express = require('express');
const app = express();

app.get('/hello', (req, res) => {
    res.json({ message: 'Hello, World!' });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

Enter fullscreen mode Exit fullscreen mode

3. Simple Object Access Protocol (SOAP):

SOAP is a protocol that uses XML for communication between services. It focuses on the structure of the messages and includes a set of standards for various aspects of communication like security and transactions. SOAP APIs can be more complex to work with compared to REST.

Implementation in Python

#main.py

from zeep import Client

client = Client('http://www.example.com/webservice?wsdl')
response = client.service.MethodName(param1=value1, param2=value2)
print(response)

Enter fullscreen mode Exit fullscreen mode

Implementation in JavaScript

// server.js

const axios = require('axios');

const requestData = `
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.example.com/webservice">
        <soapenv:Header/>
        <soapenv:Body>
            <web:MethodName>
                <web:param1>value1</web:param1>
                <web:param2>value2</web:param2>
            </web:MethodName>
        </soapenv:Body>
    </soapenv:Envelope>
`;

axios.post('http://www.example.com/webservice', requestData, {
    headers: { 'Content-Type': 'text/xml' }
})
.then(response => {
    console.log(response.data);
})
.catch(error => {
    console.error(error);
});

Enter fullscreen mode Exit fullscreen mode

4. Graph Query Language (GraphQL):

GraphQL is a query language and runtime for APIs that allows clients to request exactly the data they need. Unlike REST, where the server dictates the shape of the response, GraphQL clients specify the structure of the response. This can reduce over-fetching and under-fetching of data.

Implementation in JavaScript

// server.js 

const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { GraphQLSchema, GraphQLObjectType, GraphQLString } = require('graphql');

const app = express();

const QueryType = new GraphQLObjectType({
  name: 'Query',
  fields: {
    hello: {
      type: GraphQLString,
      resolve: () => 'Hello, world!'
    }
  }
});

const schema = new GraphQLSchema({
  query: QueryType
});

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
}));

app.listen(3000, () => {
  console.log('GraphQL server is running on port 3000');
});

Enter fullscreen mode Exit fullscreen mode

Each of these architectural styles has its own strengths and weaknesses, and the choice of style depends on factors such as the nature of the application, the communication requirements, and the development team's familiarity with the technology. This is just part of the architectural styles, others will be explained and discussed soon. Don't miss it.

You can continue to the second part of the article Here 🔥🔥🔥


Connect with me 🔥🔥

GitHub
Twitter
LinkedIn
Instagram
Facebook Page

Till the next post, Stay tuned 😍

Top comments (1)

Collapse
 
emmanuel_ayinde profile image
Engr SoluTion

Follow me for more update on #programming #softwaredevelopment. Part 2 of this is coming soon 🔥 🔥