顶级 Api 架构风格

在这篇文章中,我将深入探讨当今值得讨论的编程领域中突出的 API 架构风格,以及 Python 和 JaaScript 中的一些常见实现。

首先,什么是API?

API(应用程序编程接口)架构风格定义了软件系统的不同组件相互通信和交互的方式。
设计 API 的架构风格有多种,以下是八种主要风格:

1.远程过程调用(RPC):

RPC 涉及调用远程服务器上的过程或函数,就好像它们是本地的一样。它抽象了网络通信,并为客户端提供了一种调用远程服务方法的方法。RPC API 的示例包括 gRPC 和 XML-RPC。

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()

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());
    }
}); 

2. 具象状态传输(REST):

REST 是一种广泛且常用的架构风格,它基于一组约束来构建可扩展和可维护的 API。RESTful API 使用 HTTP 方法(GET、POST、PUT / PATCH、DELETE)对 URL 表示的资源执行 CRUD 操作。它们依赖于无状态通信并使用标准状态代码进行响应解释。

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)

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');
});

3. 简单对象访问协议(SOAP):

SOAP 是一种使用 XML 在服务之间进行通信的协议。它侧重于消息的结构,并包括一组针对通信各个方面(例如安全和事务)的标准。与 REST 相比,SOAP API 的使用可能更加复杂。

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)

JavaScript 中的实现

// server.py

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);
});

4.图查询语言(GraphQL):

GraphQL 是一种 API 查询语言和运行时,允许客户端准确请求他们需要的数据。与 REST(服务器决定响应的形状)不同,GraphQL 客户端指定响应的结构。这可以减少数据的过度获取和不足获取。

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');
});

这些架构风格中的每一种都有自己的优点和缺点,风格的选择取决于应用程序的性质、通信要求以及开发团队对技术的熟悉程度等因素。这只是建筑风格的一部分,其他的将很快解释和讨论。不要错过它。

猜你喜欢

转载自blog.csdn.net/qq_52010446/article/details/132327379