如何在Rest API中为两个外部系统实现差异化响应并识别请求来源
识别请求来源系统并返回对应响应的方案
下面是几种实用的识别方式,每种都附具体实现示例:
1. 自定义请求头识别
这是最常用的方案,让系统A和B在请求时携带专属标识头,比如X-System-Name。
举个Java Spring Boot的实现例子:
@RestController public class SystemController { @GetMapping("/api/hello") public String getHello(@RequestHeader(value = "X-System-Name", required = true) String systemName) { if ("A".equals(systemName)) { return "The system name is A"; } else if ("B".equals(systemName)) { return "The system name is B"; } return "Unknown system"; } }
用法:系统A请求时加X-System-Name: A头,系统B加X-System-Name: B头,API读取这个值就能返回对应响应。
2. URL请求参数识别
如果不方便改请求头,可以让调用方在URL里带参数,比如/api/hello?system=A。
举个Python Flask的实现例子:
from flask import Flask, request app = Flask(__name__) @app.route('/api/hello') def hello(): system_name = request.args.get('system') if system_name == 'A': return 'The system name is A' elif system_name == 'B': return 'The system name is B' return 'Unknown system' if __name__ == '__main__': app.run()
3. 固定IP地址识别
如果系统A和B有固定的公网/内网IP,可以通过请求的源IP判断。
举个Node.js Express的实现例子:
const express = require('express'); const app = express(); // 提前配置IP和系统的对应关系 const ipSystemMap = { '192.168.1.100': 'A', '192.168.1.101': 'B' }; app.get('/api/hello', (req, res) => { // 如果有反向代理,要取req.headers['x-forwarded-for']获取真实IP const clientIp = req.ip; const systemName = ipSystemMap[clientIp]; if (systemName) { res.send(`The system name is ${systemName}`); } else { res.send('Unknown system'); } }); app.listen(3000, () => { console.log('Server running on port 3000'); });
注意:如果API前面有Nginx这类反向代理,得先配置代理传递真实客户端IP,不然拿到的是代理服务器的IP。
4. API密钥/令牌识别
要兼顾安全性的话,让系统A和B携带专属的API密钥,通过密钥映射到对应系统,同时还能做身份验证。
举个Go Gin的实现例子:
package main import ( "github.com/gin-gonic/gin" "net/http" ) // 预设密钥和系统的对应关系 var apiKeyMap = map[string]string{ "key-for-system-A": "A", "key-for-system-B": "B", } func main() { r := gin.Default() r.GET("/api/hello", func(c *gin.Context) { apiKey := c.GetHeader("X-API-Key") systemName, exists := apiKeyMap[apiKey] if exists { c.String(http.StatusOK, "The system name is %s", systemName) } else { c.String(http.StatusUnauthorized, "Unknown or invalid API key") } }) r.Run(":8080") }
内容的提问来源于stack exchange,提问作者ninjacoder
相关产品推荐
相关产品推荐

