Should we use enum constants in REST API's path-params, query-params or JSON requests?

Viewed 3569

The question is regarding best practices with respect to REST APIs.

Example: I have a get API with a path-param as status.

/api/{status}

Now, in the code, the status is defined as an enum (Status). There can only be 3 (or some small finite) possible values of status.

public enum Status {
    created,
    completed,
    cancelled
}

So, should I accept "status" as a string or as Enum type?

@Path("/api/{status}")
@GET
public Response get(@PathParam("status") String status) {}
// then I can check if it is a valid status

OR

@Path("/api/{status}")
@GET
public Response get(@PathParam("status") Status status) {}
// it will throw an exception if it is an invalid status

Also, I would like to know the best-practices with respect to query-params and JSON requests as well.

1 Answers

Using enums on API, brings better design. Reasons for it are same as why we use them in general. There is compatibility between enums in programming languages that have them, and OpenApi specification https://swagger.io/docs/specification/data-models/enums/ therefore there I see no good argument against them.

Related