java 41 lines · 8 steps

Declarative HTTP clients in Spring

An annotated interface becomes a live GitHub API client through Spring's HttpServiceProxyFactory.

Explained by highlit
1public interface GitHubClient {
2 
3 @GetExchange("/users/{username}")
4 GitHubUser getUser(@PathVariable String username);
5 
6 @GetExchange("/users/{username}/repos")
7 List<Repository> listRepositories(@PathVariable String username,
8 @RequestParam(defaultValue = "updated") String sort,
9 @RequestParam(name = "per_page", defaultValue = "30") int perPage);
10 
11 @PostExchange("/user/repos")
12 Repository createRepository(@RequestHeader("Authorization") String bearerToken,
13 @RequestBody CreateRepositoryRequest request);
14 
15 @DeleteExchange("/repos/{owner}/{repo}")
16 ResponseEntity<Void> deleteRepository(@PathVariable String owner, @PathVariable String repo);
17}
18 
19@Configuration
20class GitHubClientConfig {
21 
22 @Bean
23 GitHubClient gitHubClient(WebClient.Builder builder,
24 @Value("${github.base-url:https://api.github.com}") String baseUrl,
25 @Value("${github.token}") String token) {
26 WebClient webClient = builder
27 .baseUrl(baseUrl)
28 .defaultHeader(HttpHeaders.ACCEPT, "application/vnd.github+json")
29 .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token)
30 .defaultHeader("X-GitHub-Api-Version", "2022-11-28")
31 .build();
32 
33 WebClientAdapter adapter = WebClientAdapter.create(webClient);
34 
35 HttpServiceProxyFactory factory = HttpServiceProxyFactory
36 .builderFor(adapter)
37 .build();
38 
39 return factory.createClient(GitHubClient.class);
40 }
41}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Spring can generate a working HTTP client from an interface, so you describe endpoints instead of writing request plumbing.
  2. 2Method annotations like @GetExchange and @PathVariable map Java signatures directly onto HTTP verbs, paths, and parameters.
  3. 3Centralizing base URL and auth headers in the WebClient keeps per-call methods clean and consistent.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Declarative HTTP clients in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code