Open vasanth0989 opened 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;
}
HTTP HTTPS REST SOAP
Spring/Spring Boot Gradle creating and consuming RESTFul API'
HTTP/HTTPS
TCP/IP
andUDP
Transfer Control Protocol
and UDP -User Defined Protocol
.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
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
https://example.com/api/books
. To retrieve information about a specific book with an ID of 1, the GET request would behttps://example.com/api/books/1
.2. POST
https://example.com/api/books
with the book's details (title, author, publication year, etc.) in the request body.3. PUT
https://example.com/api/books/1
with the complete new details of the book in the request body.4. PATCH
https://example.com/api/books/1
with just the new author information in the request body.5. DELETE
https://example.com/api/books/1
.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
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
Query parameters
in the URL you will find something with?
filtering
the values&
/api/accounts?type=savings&balance=2000SPIRNG 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 somestarter dependencies
that needs to be added to inorder to create a REST service.maven java project structure:
src
Gradle commands