runkar
runkar

Reputation: 466

How can I denote decimal floating point in swagger specs?

I would like to denote decimal with 2 places and decimal with 1 place in my api documentation. I'm using swagger 2.0, Is there inbuilt defined type or any other 'round' parameter in the specs, or my only option is to use 'x-' extension?

Upvotes: 19

Views: 48264

Answers (2)

Mihai
Mihai

Reputation: 53

I didn't try it myself, but try to create a Java wrapper, annnotate the wrapped field with your desired annotations (in this case, @Digits might help you), provide @Getter and @Setter with lombok, then use importMappings and typeMappings to use your custom wrapper.

For example:

@Getter
@Setter
public class MyWrapper {
    @Digits(integer = 1, fraction = 8)
    private BigDecimal bigDecimal;
}

In pom.xml file, using openapi-generator-maven-plugin.

    <importMappings>
        <importMapping>MyWrapper=my.package.MyWrapper</importMapping>
    </importMappings>
    <typeMappings>
        <typeMapping>number+digits=MyWrapper</typeMapping>
    </typeMappings>                             

In your yaml file:

    properties:
      myProperty:
        type: number
        format: digits

Upvotes: 0

Helen
Helen

Reputation: 97847

OpenAPI (fka Swagger) Specification uses a subset of JSON Schema to describe the data types.

If the parameter is passed as a number, you can try using multipleOf as suggested in this Q&A:

type: number
multipleOf: 0.1     # up to 1 decimal place,  e.g. 4.2
# multipleOf: 0.01  # up to 2 decimal places, e.g. 4.25

Hovewer, multipleOf validation against floating-point numbers can be unreliable due to floating-point math specifics.


If your number if passed as a string, you can specify a regex pattern for the desired number format:

type: string
pattern: your_regex


In any case, you can also document any restrictions verbally in the description.

Upvotes: 31

Related Questions