Printing is unavailable

This course is licensed for personal online viewing only.

Public preview • CL-P000000-C41-L1779-C6375C14

Home Dashboard
Chapter 400 · Module 9 — External Service Integration

Consuming REST APIs with RestClient

Priority
  • JobHigh
  • InterviewMedium
  • DevelopmentHigh
4,169
words
24
min read
3
tools

किसी real Spring Boot application में केवल अपना database या अपने controllers ही नहीं होते। बहुत बार application को किसी दूसरे system से data लेना पड़ता है, किसी external service को data भेजना पड़ता है, payment status check करना पड़ता है, inventory fetch करनी पड़ती है, या किसी third-party API को call करना पड़ता है।

ऐसी situation में आपका Spring Boot application खुद एक HTTP client बन जाता है।

इस chapter में हम Spring के modern synchronous HTTP client RestClient का उपयोग करके external REST APIs consume करना सीखेंगे।

1. Learning Outcomes#

इस chapter के बाद आप:

  • outbound HTTP call का basic meaning समझ पाएँगे
  • REST API provider और REST API consumer का फर्क समझ पाएँगे
  • RestClient का purpose समझ पाएँगे
  • Spring Boot के auto-configured RestClient.Builder को inject कर पाएँगे
  • external API का base URL configuration file में रख पाएँगे
  • reusable RestClient बना पाएँगे
  • HTTP GET, POST, PUT, और DELETE requests भेज पाएँगे
  • path variables और query parameters के साथ URI बना पाएँगे
  • request headers, Content-Type, और Accept configure कर पाएँगे
  • Java object को JSON request body के रूप में भेज पाएँगे
  • JSON response को Java DTO में receive कर पाएँगे
  • retrieve().body(...) और toEntity(...) का अंतर समझ पाएँगे
  • external API communication को dedicated client component में organize कर पाएँगे
  • RestClient, WebClient, और RestTemplate का high-level difference समझ पाएँगे

2. Outbound HTTP Call क्या होता है#

अब तक आपने ऐसे Spring Boot applications देखे होंगे जहाँ browser या दूसरा client आपके application को request भेजता है।

उदाहरण के लिए:

GET /products/101

यहाँ आपका Spring Boot application request receive कर रहा है।

लेकिन कभी-कभी direction उलटी होती है।

मान लीजिए आपका application किसी external inventory service से product stock पूछता है।

अब आपका application request भेज रहा है।

इसे outbound HTTP call कहा जाता है।

Key Idea

जब आपका Spring Boot application किसी दूसरे HTTP server या REST API को request भेजता है, वह outbound HTTP communication कर रहा होता है।

इस flow को देखें:

Visual Diagram80%

Rendering diagram…

यहाँ important बात यह है कि external API को इस बात से फर्क नहीं पड़ता कि request browser ने भेजी है या Spring Boot application ने।

HTTP level पर उसे एक client से request मिली है।

3. REST API Provider और REST API Consumer#

इन दोनों roles को clear रखना बहुत जरूरी है।

Role काम
REST API Provider API expose करता है और incoming requests handle करता है
REST API Consumer किसी दूसरे API को request भेजता है और response consume करता है

मान लीजिए हमारे application में endpoint है:

GET /orders/500

अगर कोई mobile application इसे call करता है, तो हमारा application provider है।

लेकिन order process करते समय हमारा application external inventory API को call करता है:

GET https://api.example.com/products/101

इस call में हमारा application consumer है।

एक ही application अलग-अलग situations में provider और consumer दोनों हो सकता है।

4. RestClient की Definition#

English Definition

RestClient is Spring's synchronous HTTP client for performing outbound HTTP requests through a fluent API.

सरल भाषा में, RestClient एक Spring API है जिसकी मदद से Java code से दूसरे HTTP server को request भेजी जा सकती है।

इसके साथ हम ऐसा flow लिख सकते हैं:

GET request → URI → headers → send request → receive response → convert response

इसका API fluent style में है, इसलिए code एक readable sequence जैसा दिखाई देता है।

उदाहरण:

JAVA
ProductResponse product = restClient.get()
        .uri("/products/{id}", 101)
        .retrieve()
        .body(ProductResponse.class);

अभी syntax को याद करने की जरूरत नहीं है।

पहले इसका meaning समझिए।

यह code कह रहा है:

  1. GET request बनाओ।
  2. /products/101 endpoint call करो।
  3. response retrieve करो।
  4. response body को ProductResponse Java object में convert करो।

5. RestClient Synchronous क्यों कहलाता है#

RestClient synchronous HTTP client है।

इसका basic meaning है कि calling thread remote response का इंतजार करता है।

मान लीजिए service method external API को call करती है।

Flow roughly ऐसा होगा:

Visual Diagram80%

Rendering diagram…

इस तरह का programming model normal imperative Spring MVC applications में natural fit होता है।

Remember

RestClient का main focus synchronous request-response communication है।

6. Example Scenario#

पूरे chapter में हम एक external Product API imagine करेंगे।

उस API के कुछ endpoints हैं:

Operation HTTP Request
Product read करना GET /products/{id}
Products filter करना GET /products?category=keyboard
Product create करना POST /products
Product update करना PUT /products/{id}
Product delete करना DELETE /products/{id}

हमारा Spring Boot application इन endpoints को consume करेगा।

7. RestClient.Builder को Inject करना#

Spring Boot application में RestClient बनाने के लिए हर जगह manually नया builder create करना अच्छा approach नहीं है।

Spring Boot एक configured RestClient.Builder provide कर सकता है जिसे dependency injection से लिया जा सकता है।

इसका फायदा यह है कि application Spring Boot की HTTP client configuration और customization mechanism के साथ रहता है।

हम एक reusable RestClient bean बनाएँगे।

पहले external API का base URL configuration में रखते हैं।

8. Base URL को Externalized Configuration में रखना#

External URL को Java class के अंदर hard-code करना avoid करना चाहिए।

ऐसा गलत pattern हो सकता है:

JAVA
RestClient.create("https://api.example.com");

यह technically काम कर सकता है, लेकिन URL बदलने पर code बदलना पड़ेगा।

Development, testing, staging और production environments में अलग URLs भी हो सकते हैं।

इसलिए configuration file बेहतर जगह है।

application.yml:

YAML
external:
  product-api:
    base-url: https://api.example.com

अब Java configuration class बनाएँ:

JAVA
package com.example.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;

@Configuration
public class RestClientConfig {

    @Bean
    public RestClient productRestClient(
            RestClient.Builder builder,
            @Value("${external.product-api.base-url}") String baseUrl) {

        return builder
                .baseUrl(baseUrl)
                .build();
    }
}

यहाँ तीन important बातें हो रही हैं।

RestClient.Builder builder Spring container से inject होता है।

baseUrl configuration file से आता है।

फिर:

JAVA
builder
        .baseUrl(baseUrl)
        .build();

एक reusable RestClient बनाता है।

अब हर request में पूरा URL लिखने की जरूरत नहीं है।

अगर base URL है:

https://api.example.com

और request URI है:

/products/101

तो final request जाएगी:

https://api.example.com/products/101

Common Mistake

External service URL को हर method में repeat करना code duplication और environment configuration problems पैदा करता है।

9. Request और Response DTOs#

External API के साथ communication के लिए dedicated DTOs रखना useful होता है।

DTO का अर्थ है Data Transfer Object।

यह object data transfer के लिए use होता है।

हम request और response के लिए अलग DTOs बनाएँगे।

JAVA
package com.example.demo.client.dto;

import java.math.BigDecimal;

public record CreateProductRequest(
        String name,
        BigDecimal price) {
}

Update request:

JAVA
package com.example.demo.client.dto;

import java.math.BigDecimal;

public record UpdateProductRequest(
        String name,
        BigDecimal price) {
}

Response:

JAVA
package com.example.demo.client.dto;

import java.math.BigDecimal;

public record ProductResponse(
        Long id,
        String name,
        BigDecimal price) {
}

यहाँ request और response अलग रखने का फायदा यह है कि external API contract साफ रहता है।

उदाहरण के लिए create request में id नहीं है क्योंकि नया product create होने के बाद server ID generate कर सकता है।

लेकिन response में id मौजूद है।

10. Dedicated API Client Component#

External HTTP calls को controller में directly लिखना avoid करना चाहिए।

उदाहरण के लिए यह architecture बेहतर है:

Visual Diagram80%

Rendering diagram…

इस structure में:

  • Controller incoming HTTP request handle करता है
  • Service business logic handle करती है
  • ProductApiClient external API communication handle करता है
  • RestClient actual outbound HTTP request भेजता है

अब client component का skeleton देखें।

JAVA
package com.example.demo.client;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;

@Component
public class ProductApiClient {

    private final RestClient restClient;

    public ProductApiClient(
            @Qualifier("productRestClient") RestClient restClient) {
        this.restClient = restClient;
    }
}

अब सारे product API calls इसी class में रखे जा सकते हैं।

इससे बाकी application को HTTP implementation details जानने की जरूरत कम हो जाती है।

11. GET Request भेजना#

सबसे पहले एक product उसके ID से fetch करते हैं।

हमारा desired endpoint है:

GET /products/101

Method:

JAVA
public ProductResponse getProduct(Long id) {
    return restClient.get()
            .uri("/products/{id}", id)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .body(ProductResponse.class);
}

Required imports:

JAVA
import com.example.demo.client.dto.ProductResponse;
import org.springframework.http.MediaType;

अब इसे step-by-step समझते हैं।

get()#

JAVA
restClient.get()

यह HTTP method GET select करता है।

हम server से data read करना चाहते हैं।

uri()#

JAVA
.uri("/products/{id}", id)

यह request URI बनाता है।

अगर id की value 101 है, तो:

{id} → 101

और final path बनती है:

/products/101

यह path variable का example है।

accept()#

JAVA
.accept(MediaType.APPLICATION_JSON)

यह server को बताता है कि client JSON response accept करना चाहता है।

HTTP level पर यह Accept header से related है।

retrieve()#

JAVA
.retrieve()

यह response processing शुरू करता है।

body()#

JAVA
.body(ProductResponse.class)

यह response body को ProductResponse Java object में map करता है।

इसलिए caller को manually JSON parse नहीं करना पड़ता।

12. Path Variables के साथ URI बनाना#

Path variable तब useful होती है जब resource identity URL path का हिस्सा हो।

उदाहरण:

/products/101

/customers/25

/orders/9001

RestClient URI template:

JAVA
.uri("/products/{id}", id)

अगर multiple variables हों, pattern इसी idea पर चलता है।

उदाहरण:

JAVA
.uri("/customers/{customerId}/orders/{orderId}",
        customerId,
        orderId)

यह manual string concatenation से ज्यादा साफ और less error-prone है।

13. Query Parameters जोड़ना#

Query parameters filtering, pagination, searching जैसी situations में common हैं।

मान लीजिए request चाहिए:

GET /products?category=keyboard&page=0

हम UriBuilder callback use कर सकते हैं।

JAVA
public ProductResponse[] getProductsByCategory(
        String category,
        int page) {

    return restClient.get()
            .uri(uriBuilder -> uriBuilder
                    .path("/products")
                    .queryParam("category", category)
                    .queryParam("page", page)
                    .build())
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .body(ProductResponse[].class);
}

यहाँ:

path("/products") endpoint path set करता है।

queryParam("category", category) category query parameter जोड़ता है।

queryParam("page", page) page parameter जोड़ता है।

अगर values हों:

category = keyboard

page = 0

तो request URI conceptually बनेगी:

/products?category=keyboard&page=0

Key Idea

Resource identity अक्सर path variable में होती है, जबकि filter, search और pagination values अक्सर query parameters में होती हैं।

14. HTTP Request Headers जोड़ना#

कभी external API को custom headers चाहिए होते हैं।

मान लीजिए API X-Client-Id header expect करती है।

JAVA
public ProductResponse getProduct(
        Long id,
        String clientId) {

    return restClient.get()
            .uri("/products/{id}", id)
            .header("X-Client-Id", clientId)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .body(ProductResponse.class);
}

यह outbound HTTP request में header जोड़ देगा।

Custom headers के common uses हो सकते हैं:

  • client identification
  • correlation IDs
  • API-specific metadata
  • authentication-related information

Authentication का detailed implementation अलग security concern हो सकता है; यहाँ focus request construction पर है।

15. Content-Type और Accept में Difference#

Beginners अक्सर Content-Type और Accept को confuse करते हैं।

दोनों अलग बात बताते हैं।

Header Meaning
Content-Type मैं जो request body भेज रहा हूँ उसका format क्या है
Accept मैं response किस format में receive करना चाहता हूँ

अगर POST request JSON body भेज रही है:

JAVA
.contentType(MediaType.APPLICATION_JSON)

अगर client JSON response चाहता है:

JAVA
.accept(MediaType.APPLICATION_JSON)

दोनों एक साथ भी use हो सकते हैं।

16. Java Object को JSON Request Body के रूप में भेजना#

अब नया product external API पर create करते हैं।

Java object:

JAVA
CreateProductRequest request =
        new CreateProductRequest(
                "Mechanical Keyboard",
                new BigDecimal("2499.00"));

Conceptually इसका JSON representation ऐसा हो सकता है:

JSON
{
  "name": "Mechanical Keyboard",
  "price": 2499.00
}

अब POST request:

JAVA
public ProductResponse createProduct(
        CreateProductRequest request) {

    return restClient.post()
            .uri("/products")
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .body(request)
            .retrieve()
            .body(ProductResponse.class);
}

इस flow को ध्यान से समझिए।

JAVA
.post()

HTTP POST method select करता है।

JAVA
.uri("/products")

target endpoint select करता है।

JAVA
.contentType(MediaType.APPLICATION_JSON)

बताता है कि outgoing request body JSON है।

JAVA
.body(request)

Java request object को request body के लिए देता है।

JAVA
.retrieve()
        .body(ProductResponse.class)

response receive करके JSON को ProductResponse में map करता है।

17. HTTP Message Conversion#

यहाँ एक important सवाल naturally आता है: Java object JSON कैसे बन गया, और JSON वापस Java object कैसे बन गया?

Spring HTTP message conversion इस काम में मदद करता है।

High-level flow देखें:

Visual Diagram80%

Rendering diagram…

जब compatible JSON support application में available होती है, Spring request DTO को JSON serialize कर सकता है और response JSON को Java DTO में deserialize कर सकता है।

इसलिए application code में हर request के लिए manually JSON string बनाने की जरूरत नहीं पड़ती।

Remember

DTO आपका Java-side representation है। JSON network पर भेजे या receive किए जाने वाले representation का common format है।

18. POST Request का Mental Model#

POST operation को इस sequence में सोचें:

Java DTO

→ request body conversion

→ JSON

→ HTTP POST

→ external server

→ JSON response

→ response conversion

→ Java response DTO

इस mental model के साथ .body(request) और .body(ProductResponse.class) का फर्क साफ हो जाता है।

पहला outgoing body है।

दूसरा incoming body का target Java type है।

19. PUT Request भेजना#

PUT अक्सर existing resource update करने के लिए use किया जाता है।

मान लीजिए endpoint है:

PUT /products/101

Method:

JAVA
public ProductResponse updateProduct(
        Long id,
        UpdateProductRequest request) {

    return restClient.put()
            .uri("/products/{id}", id)
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .body(request)
            .retrieve()
            .body(ProductResponse.class);
}

यह structure POST जैसा दिखता है, लेकिन HTTP method और URI अलग हैं।

यहाँ:

  • put() update request शुरू करता है
  • {id} target product identify करता है
  • body(request) updated values भेजता है
  • response DTO updated product represent कर सकता है

External API का exact PUT behavior उसके contract पर depend करता है।

20. DELETE Request भेजना#

अब product delete करते हैं।

Endpoint:

DELETE /products/101

अगर हमें response body की जरूरत नहीं है, तो:

JAVA
public ResponseEntity<Void> deleteProduct(Long id) {
    return restClient.delete()
            .uri("/products/{id}", id)
            .retrieve()
            .toBodilessEntity();
}

Required import:

JAVA
import org.springframework.http.ResponseEntity;

यहाँ toBodilessEntity() body expect नहीं करता, लेकिन HTTP response information ResponseEntity<Void> के रूप में मिल सकती है।

उदाहरण के लिए caller status code inspect कर सकता है।

21. retrieve().body(...) कब Use करें#

अगर आपको मुख्य रूप से response body चाहिए, यह simple approach है:

JAVA
ProductResponse product = restClient.get()
        .uri("/products/{id}", id)
        .retrieve()
        .body(ProductResponse.class);

यह common business-code scenario है।

Method का focus साफ है:

external product fetch करो और ProductResponse return करो।

22. Full Response Information कब चाहिए#

कभी केवल body काफी नहीं होती।

आपको ये सब चाहिए हो सकता है:

  • HTTP status
  • response headers
  • response body

ऐसी situation में ResponseEntity useful है।

JAVA
public ResponseEntity<ProductResponse> getProductResponse(
        Long id) {

    return restClient.get()
            .uri("/products/{id}", id)
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .toEntity(ProductResponse.class);
}

अब caller complete response inspect कर सकता है।

JAVA
ResponseEntity<ProductResponse> response =
        productApiClient.getProductResponse(101L);

HttpStatusCode status = response.getStatusCode();
HttpHeaders headers = response.getHeaders();
ProductResponse body = response.getBody();

Required imports:

JAVA
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;

Difference को compact form में याद रखें:

Need Suitable Approach
केवल mapped body चाहिए retrieve().body(...)
status + headers + body चाहिए retrieve().toEntity(...)
body नहीं चाहिए लेकिन response entity चाहिए retrieve().toBodilessEntity()

23. Complete ProductApiClient#

अब chapter में सीखे operations को एक dedicated client में combine करते हैं।

JAVA
package com.example.demo.client;

import com.example.demo.client.dto.CreateProductRequest;
import com.example.demo.client.dto.ProductResponse;
import com.example.demo.client.dto.UpdateProductRequest;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;

@Component
public class ProductApiClient {

    private final RestClient restClient;

    public ProductApiClient(
            @Qualifier("productRestClient") RestClient restClient) {
        this.restClient = restClient;
    }

    public ProductResponse getProduct(Long id) {
        return restClient.get()
                .uri("/products/{id}", id)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .body(ProductResponse.class);
    }

    public ProductResponse[] getProductsByCategory(
            String category,
            int page) {

        return restClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/products")
                        .queryParam("category", category)
                        .queryParam("page", page)
                        .build())
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .body(ProductResponse[].class);
    }

    public ProductResponse createProduct(
            CreateProductRequest request) {

        return restClient.post()
                .uri("/products")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .body(request)
                .retrieve()
                .body(ProductResponse.class);
    }

    public ProductResponse updateProduct(
            Long id,
            UpdateProductRequest request) {

        return restClient.put()
                .uri("/products/{id}", id)
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .body(request)
                .retrieve()
                .body(ProductResponse.class);
    }

    public ResponseEntity<Void> deleteProduct(Long id) {
        return restClient.delete()
                .uri("/products/{id}", id)
                .retrieve()
                .toBodilessEntity();
    }
}

यह design हमें एक important architectural advantage देता है।

Business service को यह जानने की जरूरत नहीं कि URL कैसे बन रहा है, कौन-सा header लग रहा है या कौन-सा RestClient method use हो रहा है।

Service केवल client method call कर सकती है।

उदाहरण:

JAVA
@Service
public class ProductService {

    private final ProductApiClient productApiClient;

    public ProductService(ProductApiClient productApiClient) {
        this.productApiClient = productApiClient;
    }

    public ProductResponse findProduct(Long id) {
        return productApiClient.getProduct(id);
    }
}

Required import:

JAVA
import org.springframework.stereotype.Service;

इस separation से code ज्यादा maintainable और testable बनता है।

24. Controller में Direct RestClient Calls क्यों Avoid करें#

Technically controller से RestClient call किया जा सकता है।

लेकिन बड़े application में यह जल्दी messy हो सकता है।

Controller में अगर ये सब आने लगें:

  • external URL handling
  • query parameters
  • headers
  • DTO mapping
  • response handling
  • business decisions

तो responsibilities mix हो जाती हैं।

Dedicated client component रखने पर external communication एक जगह रहता है।

Key Idea

Controller incoming web request handle करे, business service business logic handle करे, और dedicated client external HTTP communication handle करे।

25. Request Building का Reusable Pattern#

अधिकतर RestClient calls में एक recognizable flow होता है।

Visual Diagram80%

Rendering diagram…

GET में body आमतौर पर नहीं भेजी जाती।

POST और PUT में body common है।

DELETE में response body की जरूरत हमेशा नहीं होती।

इसलिए exact chain operation के अनुसार बदल सकती है।

26. RestClient और WebClient का High-Level Difference#

दोनों HTTP calls के लिए use हो सकते हैं, लेकिन उनका programming model अलग है।

Client Main Style Typical Fit
RestClient Synchronous Imperative Spring MVC applications
WebClient Reactive / non-blocking API Reactive applications और asynchronous/reactive flows

अगर आपका application normal Spring MVC imperative code use करता है और synchronous external API calls चाहिए, RestClient अक्सर straightforward choice है।

अगर application reactive programming model use करता है, WebClient अधिक natural fit हो सकता है।

यह chapter reactive programming की details में नहीं जा रहा; यहाँ सिर्फ selection का basic mental model जरूरी है।

27. RestTemplate के बारे में क्या जानना चाहिए#

पुराने Spring applications में आपको RestTemplate दिखाई दे सकता है।

इसलिए उसे पहचानना जरूरी है।

लेकिन modern synchronous HTTP client code के लिए RestClient preferred modern API है।

High-level view:

Client Awareness
RestClient Modern synchronous client
WebClient Reactive/non-blocking client API
RestTemplate Older synchronous API commonly found in legacy code

अगर existing project में RestTemplate है, तो उसे देखकर confused होने की जरूरत नहीं है।

वह historical Spring codebase में common है।

नए synchronous integration code में RestClient को समझना ज्यादा useful है।

28. Common Beginner Mistakes#

Base URL हर Method में Hard-Code करना#

इस तरह repeated URLs maintain करना मुश्किल होता है।

बेहतर approach है:

configuration property + reusable RestClient.

Path Variable Placeholder भूलना#

Incorrect intention:

JAVA
.uri("/products/id", id)

यहाँ URI template में placeholder ही नहीं है।

Correct:

JAVA
.uri("/products/{id}", id)

POST में body(request) भूलना#

अगर request object बनाया है लेकिन .body(request) नहीं लगाया, तो वह automatically request payload नहीं बन जाएगा।

JAVA
.body(request)

outgoing body attach करता है।

Content-Type और Accept को Same Meaning समझना#

Content-Type outgoing body का format बताता है।

Accept desired response format बताता है।

JSON को Manually String बनाना#

जब DTO mapping available हो, manually JSON string concatenate करना unnecessary और error-prone हो सकता है।

Java DTO देना ज्यादा maintainable होता है।

External Calls को हर Service में Repeat करना#

एक dedicated client component reuse और maintenance बेहतर करता है।

29. Request और Response Flow को एक साथ समझना#

POST request का पूरा conceptual flow देखें:

Visual Diagram80%

Rendering diagram…

इस diagram में सबसे important boundary है:

Business code Java objects के साथ काम कर रहा है।

HTTP layer JSON और HTTP metadata के साथ काम कर रही है।

RestClient और Spring message conversion इन दोनों worlds को connect करते हैं।

30. Practical Design Checklist#

External REST API integration लिखते समय यह sequence useful है:

  1. External API का base URL identify करें।
  2. Base URL configuration में रखें।
  3. Spring Boot का RestClient.Builder inject करें।
  4. Reusable RestClient बनाएँ।
  5. Dedicated request और response DTOs बनाएँ।
  6. External calls के लिए dedicated client component बनाएँ।
  7. Correct HTTP method choose करें।
  8. Path variables और query parameters safely build करें।
  9. Required headers set करें।
  10. Request body होने पर correct Content-Type set करें।
  11. Desired response format के लिए Accept set करें।
  12. Body-only या full-response retrieval requirement के अनुसार method चुनें।

31. Chapter Recap#

इस chapter से ये core ideas याद रखें:

  • Outbound call में आपका Spring Boot application HTTP client बनता है।
  • External API provider request receive करता है; consumer request भेजता है।
  • RestClient Spring का synchronous HTTP client है।
  • Spring Boot का injected RestClient.Builder reusable client configuration के लिए useful है।
  • Base URLs application configuration में रखने चाहिए।
  • .get(), .post(), .put(), और .delete() HTTP method select करते हैं।
  • .uri(...) path variables और query parameters के साथ endpoint बनाता है।
  • .header(...), .contentType(...), और .accept(...) HTTP headers configure करते हैं।
  • .body(request) Java object को outgoing request body के रूप में देता है।
  • Spring message conversion Java DTO और JSON के बीच conversion handle कर सकती है।
  • retrieve().body(...) body-focused retrieval के लिए useful है।
  • retrieve().toEntity(...) status, headers और body तीनों देता है।
  • External HTTP logic को dedicated client component में रखना clean design है।
  • Normal imperative Spring MVC applications में synchronous integration के लिए RestClient natural choice है।
  • WebClient reactive programming model से closely associated है।
  • RestTemplate पुराने Spring codebases में commonly मिल सकता है।
Interactive learning

Practice lab

Apply this chapter with guided activities, immediate feedback, explanations, and retry.

Practice loads when this section enters view.