How can I create a RESTful calculator?

后端 未结 4 1063
粉色の甜心
粉色の甜心 2021-02-01 03:32

Given that RESTful web services are all based around the sacred idea that \"everything is represented as resources and can be accessed by an address (URI)\", this may make sense

4条回答
  •  温柔的废话
    2021-02-01 04:17

    This question is couple of years old. But still seems to a question that confuses me and a lot of my colleagues. We have not been able to reach at a solution that satisfies everybody.

    But for a simple calculator, I think the below JAXRS implementation provides a clean API.

    /**
     * This class defines a CalculatorResource.
     */
    
    @Path("v{version}/calculators/{id}")
    @Named
    public class CalculatorResource {
    
        private final Long value;
    
        public CalculatorResource() {
            value = 0L;
        }
    
        public CalculatorResource(Long initialValue) {
            this.value = initialValue;
        }
    
        @GET
        public Long getValue() {
            return value;
        }
    
        @Path("+{value}")
        public CalculatorResource add(@PathParam("value") Long value) {
            return new CalculatorResource(this.value + value);
        }
    
        @Path("-{value}")
        public CalculatorResource subtract(@PathParam("value") Long value) {
            return new CalculatorResource(this.value - value);
        }
    
        @Path("*{value}")
        public CalculatorResource multiply(@PathParam("value") Long value) {
            return new CalculatorResource(this.value * value);
        }
    
    }
    

    With such an implemention, the URI can be an easy to read formula.

    Eg. /api/v1/calculators/mycalc/+9/-4/*3/+10 would return 25.

提交回复
热议问题