Quick Start
This page assumes a Spring Boot application with the dependencies installed.
1. Declare the client
Write an interface with Spring's @HttpExchange annotations and mark it with @CoApi. Put it in (or below) the package of your @SpringBootApplication class so it gets discovered automatically.
@CoApi(baseUrl = "\${github.url}")
interface GitHubApiClient {
@GetExchange("repos/{owner}/{repo}/issues")
fun getIssues(@PathVariable owner: String, @PathVariable repo: String): Flux<Issue>
}
data class Issue(val url: String)@CoApi(baseUrl = "${github.url}")
public interface GitHubApiClient {
@GetExchange("repos/{owner}/{repo}/issues")
List<Issue> getIssues(@PathVariable String owner, @PathVariable String repo);
}
record Issue(String url) {} // package-private, so both types fit in one fileIn Kotlin, escape the placeholder as \${...} so it isn't treated as string interpolation.
2. Configure the base URL
github:
url: https://api.github.comThe placeholder must resolve, or startup fails with Could not resolve placeholder 'github.url'. Use ${github.url:https://api.github.com} to give it a default.
3. Inject and call
@RestController
class IssueController(private val gitHubApiClient: GitHubApiClient) {
@GetMapping("/issues")
fun issues(): Flux<Issue> = gitHubApiClient.getIssues("Ahoo-Wang", "CoApi")
}@RestController
public class IssueController {
private final GitHubApiClient gitHubApiClient;
public IssueController(GitHubApiClient gitHubApiClient) {
this.gitHubApiClient = gitHubApiClient;
}
@GetMapping("/issues")
public List<Issue> issues() {
return gitHubApiClient.getIssues("Ahoo-Wang", "CoApi");
}
}That's it. CoApi registered a GitHubApiClient.HttpClient bean (the WebClient or RestClient) and a GitHubApiClient.CoApi bean (the proxy you injected).
Calling a discovered service
To call a service registered in service discovery, use serviceId instead of baseUrl, and add spring-cloud-starter-loadbalancer:
@CoApi(serviceId = "order-service")
interface OrderClient {
@GetExchange("orders/{id}")
fun getOrder(@PathVariable id: String): Mono<Order>
}See Load Balancing.
Where to go next
| I want to... | Read |
|---|---|
| Register clients from another package or JAR | Registering Clients |
| Override a URL per environment | Configuration Reference |
| Add headers, auth, timeouts or connection pools | Customization, Authentication |
| Understand a startup error | Troubleshooting |