API Calls

Making API calls is as simple as making function calls

Calling API endpoints between services, i.e. service-to-service calls, looks like regular function calls with Encore.ts. This gives you a simple monolith-like developer experience, even when you use multiple services. The only thing you need to do is import the service you want to call from ~encore/clients and then call its API endpoints like functions.

This works because, when compiling your application, Encore uses static analysis to parse all APIs and make them available through the ~encore/clients module for internal calls. You get all the benefits of function calls, like compile-time checking of all the parameters and auto-completion in your editor, while still allowing the division of code into logical components, services, and systems.

Example

In the example below, we import the service hello and call the ping endpoint using a function call to hello.ping.

import { hello } from "~encore/clients"; // import 'hello' service export const myOtherAPI = api({}, async (): Promise<void> => { const resp = await hello.ping({ name: "World" }); console.log(resp.message); // "Hello World!" });

Service client references

Encore uses static analysis to determine which services are calling each other. This means service client objects can't be passed around however you like, as it makes static analysis impossible in many cases.

To simplify your workflow, given these restrictions, Encore supports defining a "reference" to a service client that can be passed around any way you want. To create a reference, call the .ref() method on any service client:

import { hello } from "~encore/clients"; // Create a reference that can be passed around const helloRef = hello.ref(); // Pass the reference to other functions function doSomething(client: typeof helloRef) { return client.ping({ name: "World" }); } doSomething(helloRef);
Related example
Simple microservices example application with service-to-service API calls.
$ encore app create --example=ts/simple-event-driven