创建一个采用JSON格式并返回响应的Postneneneba API端点



我正在尝试创建一个(POST(API端点,该端点采用以下示例JSON:

{ “operation_type”: Enum <addition | subtraction | multiplication> , “x”: Integer, “y”: Integer }

运算可以是加法、减法或乘法。x可以是数字和整数数据类型。y可以是数字和整数数据类型。根据发送的操作,程序对x和y执行简单的算术运算,并返回一个包含操作结果和我的空闲用户名的响应

{ “slackUsername”: String, "operation_type" : Enum. value, “result”: Integer }

以下是我到目前为止所做的

型号

String slackUsername = "Ajava";
Integer x;
Integer y;

枚举

public enum Operator  {
addition,
subtraction,
multiplication,
unknown
}

服务

public class Service {
String operation_type;
String result;
String username;
private Operator checkType(String operation_type) {
Model model = new Model();
if (operation_type.equals("addition")) {
username =  model.getSlackUsername();
var operation = Operator.addition;
result = String.valueOf(model.getX() + model.getY());
}else if (operation_type.equals("subtraction")){
var operation = Operator.subtraction;
result = String.valueOf(model.getX() - model.getY());
} else if (operation_type.equals("multiplication")){
var operation = Operator.multiplication;
result = String.valueOf(model.getX() + model.getY());
} else {
var operation = Operator.unknown;
result = String.valueOf(model.getX() + model.getY());
}
return Operator.valueOf(this.operation_type);
}
}

控制器

@RestController
public class Controller {
Service service;
@PostMapping(path = "/operation", consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public String postOperation() {
return service.operation_type;
}
}

可以调用rest api端点。我试过了,但没有产生404错误。我想你在当地试过了。请再次检查您的http请求,并检查应用程序运行在哪个端口。

关于解决方案,它有一些问题,我已经做了一些修复和更改,请参考此代码作为示例。https://github.com/sanurah/rest-example

当服务运行时,你可以发送这样的投递请求,

样品请求:

curl --location --request POST 'localhost:8080/operation' 
--header 'Content-Type: application/json' 
--data-raw '{
"operation_type": "addition",
"x": 6,
"y": 4
}'

样品响应:

{
"slackUsername": "Ajava",
"result": 10,
"operation_type": "addition"
}

最新更新