Custom HTTPS Endpoints
On this page
You can define custom HTTPS endpoints to create app-specific API routes or webhooks that integrate with external services. A custom endpoint uses a serverless function that you write to handle incoming requests for a specific URL and HTTP method.
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' \ -H 'Accept: application/json' \ -d '{ "message": "Hello, world!" }' \ https://data.mongodb-api.com/app/myapp-abcde/endpoint/hello
Structure of an Endpoint
An endpoint handles one or more HTTP methods sent to a specific URL.
Base URL
Endpoints in an app share a base URL. The URL uses your App ID to uniquely point to your app.
Globally deployed apps use the following format:
https://data.mongodb-api.com/app/<App ID>/endpoint
Endpoints in a locally deployed app use a base URL specific to the app's
deployment region (e.g. us-east-1
)
https://<Region>.aws.data.mongodb-api.com/app/<App ID>/endpoint
Endpoint Routes
Every HTTPS endpoint has a route that serves as a name for the endpoint. An endpoint's route is arbitrary and specific to your app. However, it appears in the endpoint URL path and so should represent the action the route performs.
Route names must begin with a forward slash (/
) and may contain
additional forward slashes to indicate a nested path.
/my/nested/route
You call an endpoint by appending its route to your app's base URL and sending an HTTP request.
https://data.mongodb-api.com/app/<App ID>/endpoint/my/nested/route
HTTP Methods
Each endpoint in your app handles one or more HTTP methods for a given route. For example, you might have a
single route that accepts POST
requests to create a new resource and
a GET
request to list existing resources.
You can define multiple custom endpoints that serve the same route but handle different request methods. Alternatively, you can define a single endpoint for the route that handles all methods.
Custom endpoints support the following standard HTTP methods:
Create a Custom HTTPS Endpoint
You can configure the Data API for your app from the Atlas App Services UI or by deploying configuration files with Realm CLI:
Authentication
Custom endpoints run in the context of a specific user, which allows your app to enforce rules and validate document schemas for each request.
By default, endpoints use Application Authentication, which requires each request to include credentials for one of your application users, like an API key or JWT. You can also configure other custom authentication schemes to fit your application's needs.
New endpoints that you create in the UI use System authentication by default.
Authorization
An endpoint can require authenticated users to provide additional authorization information in the request. You define the authorization scheme for each custom endpoint by configuring the endpoint function.
Write an Endpoint Function
Every custom endpoint is associated with a function that runs whenever the endpoint receives an incoming request. In the function, you can import libraries from npm, connect to a linked MongoDB Atlas cluster, and call other serverless functions.
You define and edit endpoint handler functions on the Functions page of the Atlas App Services UI or in the /functions folder of an app configuration directory.
Endpoint functions always receive two arguments:
- A Request object that lets you access incoming request headers, query parameters, and body data.
- A Response object that you use to configure the HTTPS response sent back to the caller.
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) { try { // 1. Parse data from the incoming request if(request.body === undefined) { throw new Error(`Request body was not defined.`) } const body = JSON.parse(request.body.text()); // 2. Handle the request const { insertedId } = await context.services .get("mongodb-atlas") .db("myDb") .collection("myCollection") .insertOne({ date: new Date(), requestBody: body }); // 3. Configure the response response.setStatusCode(201); // tip: You can also use EJSON.stringify instead of JSON.stringify. response.setBody(JSON.stringify({ message: "Successfully saved the request body", insertedId, })); } catch (error) { response.setStatusCode(400); response.setBody(error.message); } }
Access Request Data
A custom endpoint Request
object represents the HTTP request that
called the endpoint. You can access the incoming request's headers,
query parameters, and body data.
{ "headers": { "<Header>": ["<Header Value>"] }, "query": { "<Query Parameter>": "<Parameter Value>" }, "body": <BSON.Binary> }
Field | Description | |||||
---|---|---|---|---|---|---|
query | An object where each field maps a URL query parameter to its value. If a key is used multiple times in the query string, only the first occurence is represented in this object. To work with the full query string, use context.request.rawQueryString. Example The following
| |||||
headers | An object where each field maps a request header name to an array of one or more values. Example
| |||||
body | A BSON.Binary object that contains the
request body. If the request did not include a body, this value
is To access data in the request body, you need to serialize the binary:
|
Return an HTTPS Response
A custom endpoint Response
object lets you configure the HTTPS
response sent back to the caller. You can set the status code, customize
headers, and include data in the response body.
Method | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|
setStatusCode(code) - code: number | Set the HTTP response status code. Example
| |||||||||
setBody(body) - body: string | BSON.Binary | Set the HTTP response body. If Example
| |||||||||
setHeader(name, value) - name: string - value: string | Set the HTTP response header specified
by Example
| |||||||||
addHeader(name, value) - name: string - value: string | Set the HTTP response header specified
by Example
|
Call a Custom Endpoint
You can call a custom endpoint from any standard HTTPS client.
curl -X GET \ -H 'api-key: <API Key>' \ -H 'Content-Type: application/ejson' \ -H 'Accept: application/json' \ --data-raw '{ "name": "Leafie", "date": { "$date": { "$numberLong": "1638551310749" } } }' https://data.mongodb-api.com/app/myapp-abcde/endpoint/hello
Choose a Response Data Format
A request can include an Accept
header to request a specific data
format for the response body, either JSON or EJSON. If a request does
not include a valid Accept
header, the response uses the default
data format specified in the endpoint configuration.
Authenticate the Request
An endpoint function can require requests to include valid credentials for an application user in the request headers. You can authenticate requests for users that log in with any of the following enabled authentication providers:
Authorize the Request
Depending on the endpoint configuration, your requests may need to include additional authorization information.