Restful Api CRUD Standard Example (Swagger 2 + validator)

Keywords: Java JSP

Why did you write this post?

To write a simple CRUD that conforms to Restful Api specification, a Controller, I want Baidu to search for a copy directly and simply modify the code in the method.

However, the search results left me speechless. None of them are in compliance with the Restful Api specification. The most speechless thing is you directly JSP page, also say Restful Api!!!

In order to make it easier for me to copy and use it later, I pasted out the copy I just wrote.

  

Swagger2: 
@Configuration
@EnableSwagger2
public class Swagger2
{
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.dj.edi.web"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("EID user CRUD")
                .description("EID user CRUD")
                .version("1.0")
                .build();
    }

}
Application: 
@SpringBootApplication
@Import(springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class)
public class ComEdiOrderUserApplication
{
    public static void main(String[] args) {SpringApplication.run(ComEdiOrderUserApplication.class, args);}

}
UserApiController:

@RestController
@RequestMapping("/v1/user")
public class UserApiController
{
    private static final Logger LOGGER = LoggerFactory.getLogger(UserApiController.class);

    @Autowired
    private ClientUsersRepository repository;

    @ApiOperation(value = "Get all user data")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseEntity<List<ClientUsers>> getClientUsersList() {
        try {
            return ResponseEntity.ok(repository.findAll());
        } catch (Exception e) {
            LOGGER.info(" Get all user data exceptions " + e.getMessage(), e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "Getting User Data")
    @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "String", paramType = "path")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<ClientUsers> getClientUsers(@PathVariable String id) {
        try {
            return ResponseEntity.ok(repository.findOne(id));
        } catch (Exception e) {
            LOGGER.info(" Getting User Data  " + id + "  Data abnormity " + e.getMessage(), e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "Create user", notes = "according to User Object Creation User")
    @ApiImplicitParam(name = "users", value = "User Detailed Entities user", required = true, dataType = "ClientUsers", paramType = "body")
    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<ClientUsers> createUser(@Valid @RequestBody ClientUsers users) {
        try {

            users.setId(ObjectId.get().toString());
            return ResponseEntity.ok(repository.save(users));

        } catch (Exception e) {
            LOGGER.info(" Create user  " + users + "  Data abnormity " + e.getMessage(), e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "Update user details", notes = "according to url Of id To specify the update object, and according to the passed user Information updates user details")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "user", value = "User Detailed Entities user", required = true, dataType = "ClientUsers", paramType = "body")
    })
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public ResponseEntity<ClientUsers> updateUser(@PathVariable("id") String id,@Valid @RequestBody ClientUsers user) {
        try {
            user.setId(id);
            return ResponseEntity.ok(repository.save(user));
        } catch (Exception e) {
            LOGGER.info(" Update user  " + user + "  Data abnormity " + e.getMessage(), e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @ApiOperation(value = "delete user", notes = "according to url Of id To specify deletion objects")
    @ApiImplicitParam(name = "id", value = "user ID", required = true, dataType = "String", paramType = "path")
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public ResponseEntity<String> deleteUser(@PathVariable String id) {
        try {
            repository.delete(id);
            return ResponseEntity.ok("ok");
        } catch (Exception e) {
            LOGGER.info(" delete user  " + id + "  Data abnormity " + e.getMessage(), e);
            return ResponseEntity.status(500).body(null);
        }
    }
}

ClientUsersRepository:
@Component
public interface ClientUsersRepository extends MongoRepository<ClientUsers, String>
{
    ClientUsers findByips(String ip);
    ClientUsers findByclientFlag(String clientFlag);
}
ClientUsers:
@Data
public class ClientUsers implements Serializable
{

    @Id
    private String id;

    /**
     * User name
     */
    @NotBlank(message = "User name cannot be empty")
    @Pattern(regexp = "^(?!string)",message = "Can not be stirng")
    private String userName;

    /**
     * ip
     */
    @NotNull(message = "ip At least one is needed.")
    private List<String> ips;

    /**
     * Identification
     */
    @NotBlank(message = " Identity cannot be empty")
    @Pattern(regexp = "^(?!string)",message = "Can not be stirng")
    private String clientFlag;

    /**
     * Customer Service ID
     */
    @NotBlank(message = "customer service ID Can not be empty")
    @Pattern(regexp = "^(?!string)",message = "Can not be stirng")
    private String checkID;
}

 

Where is the bad hope to correct?

Posted by php_guy on Sun, 10 Feb 2019 15:12:18 -0800