Home > database >  Create a Post API endpoint that takes JSON format and returns a response
Create a Post API endpoint that takes JSON format and returns a response

Time:11-06

I'm trying to create a (POST) API endpoint that takes the following sample JSON:

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

The operation can either be addition, subtraction, or multiplication. x can be a number and an integer datatype. y can be a number and an integer datatype. Based on the operation sent, the program performs a simple arithmetic operation on x and y and returns a response with the result of the operation and my slack username

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

Here is what I have done so far

Model

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

Enum

public enum Operator  {

    addition,
    subtraction,
    multiplication,
    unknown
}

Service

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

    }

Controller

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

    }

CodePudding user response:

You rest api end-point can be called. I tried and it did not produce a 404 error. I assume you tried locally. Please check your http request again and check what port the application is running in.

Regarding the solution it had some issues, I have made some fixes and changes, Refer to this code as an example. https://github.com/sanurah/rest-example

You can send a post request like this when the service is running,

Sample request:

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

Sample Response:

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