简体   繁体   中英

How to define parameter list dynamically based on request type for request model in spring boot for swagger

I am using spring boot's Rest Controller for creating rest end points. Along with swagger 2 for api documentation.

@RestController
@RequestMapping("/api")
public class BatchController extends ControllerConfig {

    @PostMapping("/batch")
    public GeneralResponse<Boolean> createBatch(@RequestBody Batch batch) throws Exception{
        try{
            batchService.createBatch(batch);
            return new GeneralResponse<>(true,"batch created successfully", true, System.currentTimeMillis(), HttpStatus.OK);
        } catch (Exception e){

            return new GeneralResponse<>(false,e.getMessage(), false, System.currentTimeMillis(), HttpStatus.BAD_REQUEST);
        }
    }


    @PutMapping("/batch")
    public GeneralResponse<Boolean> updateBatch(@RequestBody Batch batch) {
        try {
            batchService.updateBatch(batch);
            return new GeneralResponse<>(true, "batch updated successfully", true, System.currentTimeMillis(), HttpStatus.OK);
        } catch (Exception e) {
            return new GeneralResponse<>(false, e.getMessage(), false, System.currentTimeMillis(), HttpStatus.BAD_REQUEST);

        }
    }

}

And Batch Model :

@Entity
@Table
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Batch {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Long qualityId;
    private Date date;
    private String remark;
}

I am using JPA repository.

Now, For both the rest end points Swagger will show the request model as :

{
    id: 0,
    qualityId: 0,
    date: "2020-10-04T21:18:00.656Z",
    remark: "string"
}

but I want to hide "id" field for create batch request as that is autogenerated, but its required for update as that is based on id.

how can that be done?

Entities are not supposed to be exposed in the API layer, You should create a dedicated DTO classes instead.

For example-

@Data
public class PutBatchDTO {
    private Long id;
    private Long qualityId;
    private Date date;
    private String remark;
}

@Data
public class PostBatchDTO {
    private Long qualityId;
    private Date date;
    private String remark;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM