Creating APIs

Encore makes it easy to create and call API endpoints.

Creating an API endpoint

To create an API endpoint, you create a regular function in a Go package. The function takes as input a data structure (the request schema) and returns another data structure (the response schema). Lastly, to indicate that the function should be an API endpoint, you add the // encore:api magic comment right above the function definition.

It looks like this:

package my_service

type InputData struct {
    Name string
}

type OutputData struct {
    Message string
}

// MyEndpoint is an example endpoint.
// encore:api public
func MyEndpoint(input *InputData) *OutputData {
    message := "Hello, " + input.Name
    return &OutputData{Message: message}
}

Notice how we only have to care about what the input data is, and what the output data is, and the logic inside the function. Encore takes care of everything else.

Calling an API endpoint

Now that we have an API endpoint we would like to call it. By default API endpoints are private, meaning they are only accessible to other backend services in your application. In the example code above we used the public keyword in the API declaration to make it publicly available already.

To call the API endpoint, run the below curl command in your terminal:

curl https://docs.encoreapi.com/b8a3f00e/my_service.MyEndpoint \
-d '{"Name": "John Doe"}'

Subscribe to our Engineering Blog

The latest ideas to help you build better software.

You can unsubscribe at any time.

© 2020 Encore. All rights reserved.