Docs Menu

HTTPS Endpoints

On this page

  • Introduction
  • Endpoint Routes
  • HTTP Methods
  • Endpoint Functions
  • Requests & Responses
  • Request Objects
  • Response Objects
  • Return Types
  • Return Type Override
  • Authentication
  • System Authentication
  • Application Authentication
  • Authorization
  • Secret Query Parameter
  • Payload Signature Verification
Note

HTTPS endpoints replace webhooks from Realm's deprecated third-party service integrations. To learn how to migrate your existing webhooks, see Convert Webhooks to HTTPS Endpoints.

HTTPS endpoints are serverless functions that you call by sending requests from an HTTP client. An endpoint receives requests sent to a URL, runs a function that can access data from the request payload, and then returns a result back to the caller. You can use endpoints to define custom API routes for your app or webhooks that integrate with external services.

Endpoints use standard, encrypted HTTPS requests, which means that you don't need to install any database drivers or opinionated libraries to call them. Instead, you send requests like this from any HTTP client:

curl -X POST \
-H 'api-key: <API Key>' \
-H 'Content-Type: application/json' \
-d '{ "message": "Hello, world!" }' \
https://data.mongodb-api.com/app/myapp-abcde/endpoint/hello

Every HTTPS endpoint has a unique route that serves as a name for the endpoint. You call an endpoint by appending its route to your app's base URL and sending an HTTP request. Route names must begin with a forward slash (/) and may contain additional forward slashes to indicate a nested path.

Endpoint URL Format (Global Apps)
https://data.mongodb-api.com/app/<App ID>/endpoint/<Route>

Endpoints in a locally deployed app use a base URL specific to the app's deployment region (e.g. us-east-1):

Endpoint URL Format (Local Apps)
https://<Region>.aws.data.mongodb-api.com/app/<App ID>/endpoint/<Route>

You can configure an endpoint to accept only a specific HTTP method or allow any method and handle each type within the endpoint function.

HTTPS endpoints support the following standard HTTP methods:

Each request sent to an HTTPS endpoint calls an associated serverless function that handles the logic for the endpoint. The function runs your custom code and can import libraries from npm, connect to a linked MongoDB Atlas cluster, and call other serverless functions.

Tip

You define and edit endpoint handler functions on the Functions page of the Realm UI or in the /functions folder of an app configuration directory.

Endpoint functions receive arguments that describe the incoming request and allow you to modify the response sent back to callers.

Endpoint function signature
exports = async function (request, response) {
// ... your code here
}
Example

This endpoint function parses the body of an incoming POST request, stores the parsed body in a MongoDB collection, and then responds to the caller:

exports = async function (request, response) {
// 1. Parse the incoming request
const bodyJson = JSON.parse(request.body.text());
// 2. Run the endpoint logic
await context.services
.get("mongodb-atlas")
.db("myDb")
.collection("myCollection")
.insertOne({ date: new Date(), requestBody: bodyJson });
// 3. Configure the response
response.setBody("Request was successful");
}

The first argument of an endpoint function is a request object that includes information about the incoming HTTP request that called the endpoint.

Endpoint Request Object
{
"query": { "<Query Parameter>": "<Parameter Value>" },
"headers": { "<Header>": ["<Header Value>"] },
"body": <BSON.Binary>
}
Field
Description
query
An object where each field maps a URL query parameter to its value.
headers
An object where each field maps a request header name to an array of one or more values.
body
A BSON.Binary object that contains the request body. If the request did not include a body, this value is undefined.

The second argument of an endpoint function is a response object that represents HTTPS response sent back to the caller. The object includes methods that you can call to configure the response.

Note
Difference in Response Converting from Webhooks to Endpoints

If you're converting your webhooks to endpoints, there can be slight differences in behavior for how your Realm function handles the the HTTP response. For more information, refer to the documentation on differences between webhooks and their converted endpoints.

Method
Description
setStatusCode(code)
- code: number

Set the HTTP response status code.

Example
response.setStatusCode(201);
setBody(body)
- body: string | BSON.Binary

Set the HTTP response body.

If body is a string, it will be encoded to BSON.Binary before being returned.

Example
response.setBody(
"{'message': 'Hello, World!'}"
);
setHeader(name, value)
- name: string
- value: string

Set the HTTP response header specified by name to the value passed in the value argument. This overrides any other values that may have already been assigned to that header.

Example
response.setHeader(
"Content-Type",
"application/json"
);
addHeader(name, value)
- name: string
- value: string

Set the HTTP response header specified by name to the value passed in the value argument. Unlike setHeader, this does not override other values that have already been assigned to the header.

Example
response.addHeader(
"Cache-Control",
"max-age=600"
);
response.addHeader(
"Cache-Control",
"min-fresh=60"
)

Endpoints can return data as JSON or MongoDB Extended JSON (EJSON).

You can control the default response encoding with the Return Type option in your endpoint configuration:

the return type option in endpoint configuration
Note
EJSON to JSON Translation May Lose Information

MongoDB stores data as BSON and uses MongoDB Extended JSON, or EJSON, to represent types that do not exist in the JSON format. When you use the JSON return type, endpoints translate fields into JSON values when possible and omit the values of EJSON fields that have no JSON equivalent.

To avoid any field value translations or omissions, configure your endpoint to respond with EJSON.

When calling an endpoint, use the Accept header to control the response type:

Tip
See also:

For more information about the differences between JSON and EJSON responses, see the Atlas Data API documentation.

Endpoint requests can run as either an unauthenticated system user or an application user. Most endpoints use either system authentication or appplication authentication.

Tip

New endpoints that you create in the UI use System authentication by default.

If the endpoint function is configured to run as the system user, incoming requests do not need to include any user credentials or tokens. The endpoint will not enforce any Rules or validate your Schemas.

If the endpoint function is configured to use application authentication, incoming requests must include one or more headers that contain valid user credentials. Users can authenticate with any of the following configured authentication providers:

  • Email/Password

    curl -X GET \
    -H 'email: <Email Address>' \
    -H 'password: <Password>' \
    -H 'Content-Type: application/json' \
    https://data.mongodb-api.com/app/myapp-abcde/endpoint/test
  • API Key

    curl -X GET \
    -H 'api-key: <API Key>' \
    -H 'Content-Type: application/json' \
    https://data.mongodb-api.com/app/myapp-abcde/endpoint/test
  • Custom JWT

    curl -X GET \
    -H 'jwtTokenString: <Custom JSON Web Token>' \
    -H 'Content-Type: application/json' \
    https://data.mongodb-api.com/app/myapp-abcde/endpoint/test

You can configure authorization for each endpoint to determine whether or not an authenticated request is allowed to execute.

HTTP endpoints always enforce Rules in the context of the authenticated user that called the endpoint. In addition, you can specify a request validation scheme that requires incoming requests to incorporate a secret value.

You can specify up to one of the following schemes:

Note

For maximum security, programmatically generate the secret value using a secure package such as the Python secrets module. Make sure that you do not publish the secret or include it in your version control system.

The secret query parameter request validation option requires that incoming requests include the secret value as a query parameter appended to the end of the URL.

Every request must include the secret value as the secret query parameter:

<endpoint URL>?secret=12345
Example

The following curl request uses secret query parameter validation with the secret value 12345:

curl -X POST \
-H "Content-Type: application/json" \
-d '{ "message": "HELLO" }' \
https://data.mongodb-api.com/app/myapp-abcde/endpoint/testSecretQueryParam?secret=12345

Payload signature verification requires that incoming requests include an HTTP header where the value is a hexadecimal-encoded HMAC SHA-256 hash generated from the request body and the secret value.

You could use the following function to generate the payload signature:

// Generate an HMAC request signature
exports = function signEndpointRequest(
secret, // the secret validation string e.g. 12345
body, // the endpoint request body e.g. { "message": "MESSAGE" }
) {
return utils.crypto.hmac(EJSON.stringify(body), secret, "sha256", "hex");
}

Every request must include a payload signature in the Endpoint-Signature header:

Endpoint-Signature::sha256=<hex encoded hash>
Example

The following curl request demonstrates payload signature verification with the secret value 12345:

curl -X POST \
-H "Content-Type: application/json" \
-H "Endpoint-Signature::sha256=828ee180512eaf8a6229eda7eea72323f68e9c0f0093b11a578b0544c5777862" \
-d '{"message":"MESSAGE"}' \
https://data.mongodb-api.com/app/myapp-abcde/endpoint/testPayloadSignatureVerification
←  GraphQL Types, Resolvers, and OperatorsCreate an HTTPS Endpoint →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.