EzyHTTP Handle Requests

Updated at 1685707948000
EzyHttp allows you handle client request vi Controller with GET, POST, PUT, DELETE methods

1. Handle Get Request

You can handle a get request with a method and @DoGet annotation. EzyHttp allows you pass parameter via query parameters or path variable, example:

    @DoGet("/books/{bookId}")
    public BookResponse getBook(@PathVariable Long bookId) {
        final BookData bookData = bookService.getBook(bookId);
        return dataToResponseConverter.toResponse(bookData);
    }
    @DoGet("/books")
    public List getBooks(
        @RequestParam("lower_than") String lowerThan,
        @RequestParam("upper_than") String upperThan,
        @RequestParam("size") int size
    ) {
        final List dataList = bookService.getBooks(
            lowerThan,
            upperThan,
            size
        );
        return dataToResponseConverter.toResponseList(dataList);
    }

You can find out full source code in BookController Example Use path variable make our code more clearer and it makes our APIs become resource oriented. But when we have many parameters we should use request query parameters

2. Handle Post Request

Get request does not accept an body. So for a create or update API we should use POST method. Of course you still can use path variable and query parameters with a POST request, example:

    @DoPost("/book/add/{count}")
    public boolean addBooks(@PathVariable int count) {
        bookService.addBooks(count);
        return Boolean.TRUE;
    }
    @DoPost("/book/add")
    public BookResponse addBook(@RequestBody AddBookRequest request) {
        bookValidator.validate(request);
        final AddBookData addBookData = requestToDataConverter.toData(request);
        final BookData bookData = bookService.addBook(addBookData);
        return dataToResponseConverter.toResponse(bookData);
    }

You can find out full source code in BookController Example

3. Handle Put Request

Same as the POST method, but PUT method is suitable for update APIs, example:

    @DoPut("/books/{bookId}")
    public ResponseEntity getBook(
        @PathVariable Long bookId,
        @RequestBody UpdateBookRequest request
    ) {
        bookService.updateBook(requestToModelConverter.toModel(request));
        return ResponseEntity.noContent();
    }

4. Handle Delete Request

If you want to delete a resource, you should use a delete API, but delete method does not accept an request body so we need use path variable or query parameters, but path variable is a better idea, example

    @DoDelete("/books/{bookId}")
    public ResponseEntity getExpectedRevenue() {
        bookService.delete(bookId);
        return ResponseEntity.noContent();
    }

You can find out full source code in BookController example

5. Next

We can handle which exceptions that throw from controllers.