Skip to main content

RADUS#3 - CRUD and REST API's (focus on HTTP Methods, Annotations and no DB)

 

90% of the time services does CRUD operations with REST over HTTP protocol so in this post we'll look into different HTTP methods and annotations we can use to communicate with the service to perform crud operations. 

We'll be building a simple todo API where you can:

  • Create a todo (method: HTTP POST, endpoint: **/api/1/0/todos)
  • Read list of todos (method: HTTP GET, endpoint: **/api/1/0/todos)
  • Read a single todo (method: HTTP GET, endpoint: **/api/1/0/todos/{id})
  • Delete a todo (method: HTTP DELETE, endpoint: **/api/1/0/todos/{id})
**To keep things simple and not shift the focus out of the controller class, we will store all these todos in in-memory using a simple Map

controller code using java:
package com.artifactsbyrake.restdemo.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;

@RestController
@RequestMapping("/api/1/0")
public class TodoController {

    private int seq = 1;

    private Map<Integer, String> todos = createDefaultTodos();

    private Map<Integer, String> createDefaultTodos() {
        Map todoMap = new HashMap();
        IntStream
                .range(seq, 5)
                .forEach(i -> {
                    seq = i;
                    String todo = "Todo - " + seq;
                    todoMap.put(seq, todo);
                });
        return todoMap;
    }

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello Rest demo";
    }

    @GetMapping("/todos")
    public ResponseEntity<Map> getListOfTodos() {
        return ResponseEntity.ok(todos);
    }

    @GetMapping("/todos/{id}")
    public ResponseEntity<String> getTodo(@PathVariable int id) {
        if (id < 0)
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid ID - Please provide a valid ID and retry");

        if (!todos.containsKey(id))
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No todo found with ID");

        return ResponseEntity.ok(todos.get(id));
    }

    @PostMapping("/todos")
    public ResponseEntity<Object> addTodo(@RequestBody String todo) {
        if (ObjectUtils.isEmpty(todo))
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Empty todo");

        todos.put(++seq, todo + " - " + seq);
        URI todoLoc = ServletUriComponentsBuilder.fromCurrentRequest()
                        .path("/{id}")
                        .buildAndExpand(seq)
                        .toUri();
        return ResponseEntity.created(todoLoc).build();
    }

    @DeleteMapping("/todos/{id}")
    public ResponseEntity<Object> deleteTodo(@PathVariable int id) {
        if (id < 0)
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid ID - Please provide a valid ID and retry");

        if (!todos.containsKey(id))
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No todo found with ID");

        todos.remove(id);

        return ResponseEntity.noContent().build();
    }
}

Whenever you hit a HTTP request (http://localhost:9000/api/1/0/todos), Spring handles the request using controllers which are usually annotated with @RestController

@RequestMapping
  • This annotation is used to map requests onto a class or method which can handle the request. 
  • These days this annotation is used mostly at class level and specific composed annotations like @GetMapping are used at method level
@GetMapping, @PutMapping, @PostMapping...
  • These annotations are used mostly at method level to map requests onto specific handler methods which can handle those GET, PUT and POST requests
ResponseEntity<Type>
  • This is the extension of HttpEntity along with an HttpStatus code
  • As shown in the code ResponseEntity.ok(todos.get(id)); you can set the standard HttpStatus codes to communicate the status of the request

ResponseStatusException
  • You throw this exception when you want to communicate any scenario to the client where you're not able to complete the request

You can find source code here


Happy Coding  👨‍💻
















Comments

Popular posts from this blog

Spring Boot - RestTemplate PATCH request fix

  In Spring Boot, you make a simple http request as below: 1. Define RestTemplate bean @Bean public RestTemplate restTemplate () { return new RestTemplate (); } 2. Autowire RestTemplate wherever you need to make Http calls @Autowire private RestTemplate restTemplate ; 3. Use auto-wired RestTemplate to make the Http call restTemplate . exchange ( "http://localhost:8080/users" , HttpMethod . POST , httpEntity , String . class ); Above setup works fine for all Http calls except PATCH. The following exception occurs if you try to make a PATCH request as above Exception: I / O error on PATCH request for \ "http://localhost:8080/users\" : Invalid HTTP method: PATCH ; nested exception is java . net . ProtocolException : Invalid HTTP method: PATCH Cause: Above exception happens because of the HttpURLConnection used by default in Spring Boot RestTemplate which is provided by the standard JDK HTTP library. More on this at this  bug Fix: This can b...

Settings.xml for Maven, JFrog

For development and deployment of applications we always use an artifactory in real-time world to host artifacts needed for your build and also as a target to deploy artifacts generated in the build process. For Maven, to communicate with artifactory we need a settings.xml file which is usually located at "/User/rake/.m2/settings.xml" this file consists of how to authenticate to the artifactory servers and authorizations to read/ write to different locations like release, snapshots e.t.c... Settings.xml can be generated using the artifactory you're using which in my case is JFrog , but here's a sample settings file for your reference incase you're feeling lazy☺ <?xml version="1.0" encoding="UTF-8"?> <settings xsi:schemaLocation= "http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd" xmlns= "http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi= "http://www.w3.org/2001/XM...

Stored Procedures in ADF

One of the common requirements for ADF programmers is to invoke Stored Procedures and Functions. Implementing this is so simple with few lines of code in Java classes used under business components. Following code snippets from fusion guide  will help execute different procedures with and without arguments. Execute stored procedure with No Arguments: public void callProcWithNoArgs() { getDBTransaction().executeCommand( "begin devguidepkg.proc_with_no_args; end;"); } Execute stored procedure with only IN arguments: Procedures often take arguments in order to process some business logic. Arguments are limited from none to many. In order to use stored procedures with argument mode we need to use JDBC PreparedStatement object. How To: Create connection Create a JDBC PreparedStatement with procedure details wrapped in a PL/SQL begin..end block. Assign the values to arguments if any. Execute the statement. Close the statement. protected void callStoredPr...