vasanth0989 / prep-myself

0 stars 0 forks source link

Spring Boot Introduction #15

Open vasanth0989 opened 8 months ago

vasanth0989 commented 8 months ago

HTTP HTTPS REST SOAP

Spring/Spring Boot Gradle creating and consuming RESTFul API'

HTTP/HTTPS

Client -> server
https://www.google.com
Internet Packets -> 

source <-> destination
chunked, broken down -> internet packets

https://www.google.com TCP/IP -> guarnatess order of the data
checksum value

http - port 80
https - port 443

tcp
TLS over - https 
http

3 way Handshake - TCP Handshake client -> server (SYN) Client <- Server (SYN/ACK) client -> server (ACK)

SSL/TLS -> Transport Layer Security V1.3 Encryption algorithm

types of encryption

  1. Symmetric - key to encrypt the data DES, AES, - obselte 3AES - same key to decrypt the data
  2. Asymmetric encryption - public/private key pair EC - Elipic curve DiffieHellmanKeyExchange Algorithm

RSA -> you need to generate a key pair private key will be residing at the server public key -> this can be shared to others

client needs to send the data to the server public key to encrypt the data private key to decrypt the data http -> it is over TCP - is not encrypted DNS lookup ->

Application protocols HTTP -> TCP -> HyperText Transfer Protocol

SOAP - is a protocol goes via HTTP METHOD POST

method Names SOAP operation -> getBooks XML -> JAXB -> Marshall and Unmarshalling marshall -> convert your java objects to XML unMarshalling -> convert xml to Java objects WSDL - WebServiceDefinitionLanguage contract

REST - Architectural style 4 core important things:

REST - RepresentationalStateTransfer -> RESOURCE REST -> it works on URI -> /api/books HTTP methods GET - /api/books IDEMPOTANT - no RequestBody POST - /api/books Creating a new data -> requestBody PUT - /api/books/1 You are updating the entire data for a particular id PATCH - /api/books/1 are updating only the little part of the data DELETE - /api/books/1 You are removing the data

To explain the operation of the HTTP methods GET, POST, PUT, PATCH, and DELETE, let's use a simple example of a web service for managing a book collection. This web service allows users to view, add, update, and delete books in the collection.

Base URL

Assume the base URL for the web service is: https://example.com/api/books

1. GET

2. POST

3. PUT

4. PATCH

5. DELETE

Summary

Each of these methods plays a crucial role in RESTful API design, allowing for clear and standardized interactions with web resources.

HTTP METHOD: GET - /api/books IDEMPOTANT - no RequestBody - HTTP STATUS: 200 HTTP HEADERS: REQUEST/RESPONSE HEADERS HTTP_AUTH_TOKEN Accept - application/json

POST - /api/books Creating a new data -> requestBody - HTTP STATUS: 201 HTTP HEADER: ContentType- application/json Accept PUT - /api/books/1 You are updating the entire data for a particular id: 200 PATCH - /api/books/1 are updating only the little part of the data: 200 DELETE - /api/books/1 You are removing the data: 204

HTTP Status https://httpstatuses.io/

2xx 200 - is for the OK status from the server 201 - data has been created on server 204 - it is a OK status but with no content, there won't be any response body

4xx - Client side error 400 - is for a BAD request, say you are sending some invalid data as par of the post request.

Authentication and Authorizaion 401 and 403

Authentication -> you have username/password you are trying to authenticate the system. -> If your authentication is not successfull you are gonna get the Authorization Error, invalid username/password with the HTTP Status code of 401. Authorization -> You successfully authenticated to the system -> but you don't have proper access, like say you are not admin and you are trying to perform admin actions, you are gonna ge 403 - Forbidden error.

404 -> particular resource is not found, you are trying to access the data which is not present.

422 - UnprocessableEntity - ConstraintVoilationException

5xx 500

PathVariables & Request Parameters

PathVariables

Request Parameters


SPIRNG stuff -> we will be creating 3 different operations -> GET api/v1/accounts -> to fetch the list of accounts - 200 -> POST api/v1/accounts/1 -> to fetch individual account - 201 -> GET api/v1/acccounts?type=CHK -> to fetch the list of accounts matching that filter - 200 -> DELETE api/v1/accounts/1 - 204

Spring -> Dependency Injection -> IOC - Inversion of Control

Controller -> Service have all the coding logic

@Autowired -> used for injecting the bean

Application context -> is a wrapper over JVM Spring realated objects resides Infrastructure Beans -> Spring framework creates itself to serve the Web appliciation UserDefined Beans -> we create

Sterotype annotations

@Controller @Component @Service

@Configuration -> this is the class where you are going to define the beans

@Service -> creating the object for us, IOC -> adding it to the application context

within @Configuration class you can create your own bean

@Bean RestTemplate restTemplate(){ return new RestTemplate(); }

Gradle -> is a build tool

Spring vs Spring boot

Spring boot does all the heavy lifting

With Just Spring -> you need to take care of all dependencies manually there might be dependency conflict -> you need to manually create all the beans yourself and you need to write lot of boiler plate code.

With Spring Boot Autoconfiguration -> this has become easy. Spring boot itself is going to configure the beans for us, we need to write all the boiler plate codes.

Spring boot comes with Embedded Tomcat server

We will use https://start.spring.io/ - Spring Intializr to create the Spring boot project. -> there are some starter dependencies that needs to be added to inorder to create a REST service.

maven java project structure:

src


Gradle commands

# to build the project, before running this command make sure you have Java 17
# to build the project
./gradlew clean build
# to build the project and skip executing the tests
./gradlew clean build -x test
# this to run the project
./gradlew bootRun
# this is to view the dependencies tree
./gradlew -q dependencies > dep_graph.txt
vasanth0989 commented 8 months ago
package com.example.accounts.controller;

import com.example.accounts.pojo.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@RequestMapping("/api/v1")
@RestController
@Slf4j
public class AccountsController {

    private static List<Account> accounts = new ArrayList<>();

    static {
        accounts.add(Account.builder().id(1).type("CHK").build());
        accounts.add(Account.builder().id(2).type("SVG").build());
        accounts.add(Account.builder().id(3).type("CHK").build());
        accounts.add(Account.builder().id(4).type("IRA").build());
    }

    @GetMapping("/accounts")
    public ResponseEntity<List<Account>> getAccounts(@RequestParam(name = "type", required = false) String type) {
        if (StringUtils.hasText(type)) {
            return ResponseEntity.ok(accounts.stream().filter(acct -> acct.getType().equalsIgnoreCase(type)).collect(Collectors.toList()));
        }
        return ResponseEntity.ok(accounts);
    }

    @GetMapping("/accounts/{id}")
    public ResponseEntity<Account> getAccountById(@PathVariable Integer id) {
        return ResponseEntity.ok(accounts.stream().filter(account -> account.getId() == id).findFirst().orElseThrow());
    }

    @PostMapping("/accounts")
    public ResponseEntity<Account> createAccount(@RequestBody Account account) {
        accounts.add(account);
        return new ResponseEntity<>(account, HttpStatus.CREATED);
    }

    @DeleteMapping("/accounts/{id}")
    public ResponseEntity<Account> createAccount(@PathVariable Integer id) {
        int index = IntStream.range(0, accounts.size()).filter(i -> accounts.get(i).getId() == id).findFirst().orElseThrow();
        accounts.remove(index);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

}
package com.example.accounts.pojo;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Account {

    private int id;
    private String type;
}