The Data API lets you securely read and write data using standard HTTPSrequests. The API includes automatically generated endpoints that eachrepresent a MongoDB operation. You can use the endpoints to create,read, update, delete, and aggregate documents in a MongoDB data source.
For example, thisPOST request stores adocument in a linked cluster by calling theinsertOne endpoint:
curl -s"https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/insertOne" \ -X POST \ -H"Content-Type: application/ejson" \ -H"Accept: application/json" \ -H"apiKey: TpqAKQgvhZE4r6AOzpVydJ9a3tB1BLMrgDzLlBLbihKNDzSJWTAHMVbsMoIOpnM6" \ -d'{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "hello", "document": { "text": "Hello, world!" } }'
{"insertedId":"5f1a785e1536b6e6992fd588"}
For a detailed API reference of all available endpoints, see theData API OpenAPI Reference.
Note
Data API Endpoints are not supported inprivate endpoints.
When to Use the Data API
You can use the Data API to integrate with any app or service thatsupports HTTPS requests. For example, you might:
query Atlas from a mobile application
access test data and log events in a CI/CD workflow
integrate Atlas into a federated API gateway
connect from an environment not currently supported via a MongoDBDriver or Realm SDK
An operation called through an API endpoint will likely take longer thanthe corresponding MongoDB operation called through a connected MongoDBDriver. For high-load use-cases and latency sensitive applications, werecommend connecting directly to your database with a MongoDB driver. Tolearn more, visit theMongoDB Drivers documentation.
Base URL
The Data API endpoints in an app share a base URL. The URL uses your AppID to uniquely point to your app and specifies which version of the DataAPI to call. Each endpoint has a unique URL formed by appending theendpoint's route to your app's base URL.
Globally deployed apps use the following format:
https://data.mongodb-api.com/app/<App ID>/endpoint/data/<API Version>
Endpoints in a locally deployed app use a base URL specific to the app'sdeployment region (e.g.us-east-1.aws):
https://<Region>.<Cloud>.data.mongodb-api.com/app/<App ID>/endpoint/data/<API Version>
Set Up the Data API
You can configure the Data API for your app from the App Services UI or bydeploying configuration files with App Services CLI:
ClickHTTPS Endpoints in the left navigation menu and thenselect theData API tab.
Enable the Data API for your app. This generates endpoints thatcan access any MongoDB data source linked to your app.
Choose anauthenticationmethod and enable authentication providers.
Choose aresponse type.
Save the Data API configuration.
Configureaccess permissions bydefining rules for collections in your linked data sources toallow requests to securely read and write data.
Save and deploy your app.
Pull the latest version of your app.
appservices pull --remote="<Your App ID>" Define a Data API configuration file.
https_endpoints/data_api_config.json{ "disabled":false, "versions": ["v1"], "can_evaluate": {}, "return_type": <"JSON" |"EJSON"> } Deploy your app.
appservices push
Authentication
Data API endpoints run in the context of a specific user, which allowsyour app to enforce rules and validate document schemas for eachrequest.
By default, endpoints use Application Authentication, which requireseach request to include credentials for one of your application users,like an API key or JWT. You can also configure other customauthentication schemes to fit your application's needs.
For examples of how to authenticate requests, seeAuthenticateData API Requests.
Application authentication requires users to log in with anauthentication provider that you have enabled for your App.Requests can either include an access token granted by theauthentication provider or the credentials the user would log inwith (e.g. their API key or email and password).
User ID authentication runs all requests as a single, pre-selectedapplication user. This is useful if all requests should have thesame permissions regardless of who called the endpoint.
To select the user, specify their User Account ID in your app'sData API configuration.
{ "run_as_user_id":"628e47baf4c2ac2796fc8a91" }
Script authentication calls a function to determine whichapplication user a request runs as. You can use this to implementcustom authentication and authorization schemes.
The function must return an existing application user's Account IDas a string or{ "runAsSystem": true } to run the requestas asystem user that has full access toMongoDB CRUD and Aggregation APIs and is not affected by anyrules, roles, or permissions.
To define the function, specify the source code in your app's DataAPI configuration.
[ { ..., "run_as_user_id_script_source":"exports = () => {return\"628e47baf4c2ac2796fc8a91\"}" } ]
Authorization
You can require authenticated users to provide additional authorizationinformation in each request. You define the authorization scheme forall generated Data API endpoints in your Data API configuration.
Endpoints natively support a set of built-in authorization schemes thatuse a secret string to prove that the request is authorized. You canalso define a custom authorization scheme that you can use together withor instead of the built-in schemes.
Built-In Authorization Schemes
Endpoints support the following built-in authorization schemes:
All authenticated users are authorized to call the endpoint.Authenticated requests do not need to include authorizationinformation.
Authenticated users must prove that they are authorized to callthe endpoint by including a specific string as the value of thesecret query parameter.
You define the string in asecret andreference the secret by name in the endpoint configuration.
[ { ..., "verification_method":"SECRET_AS_QUERY_PARAM", "secret_name":"secret_verification_string" } ]
To learn how to include the secret in a request, seeAuthorize the Request.
Authenticated users must prove that they are authorized to callthe endpoint by including anEndpoint-Signature header thatcontains a hexadecimal-encodedHMAC SHA-256 hash generated from the request bodyand a secret string.
You define the string in asecret andreference the secret by name in the endpoint configuration.
To learn how to sign your requests, seeAuthorize the Request.
Custom Authorization Schemes
You can define a custom authorizationexpression todetermine if an incoming authenticated request is allowed to run. Theexpression is evaluated for each request and must evaluate totrueto allow the request. If the expression evaluates tofalse, therequest is not authorized and fails with an error. Requests that failauthorization are not counted toward your App's billed usage.
Authorization expressions can use variables like%%user to authorize based on the calling user's dataor%%request to make decisions based on the specificsof each incoming request.
To define a custom authorization scheme, specify the expression in yourapp's Data API configuration:
{ ..., "can_evaluate":{ "%%request.requestHeaders.x-secret-key":"my-secret" } }
Response Type
Endpoints can return data in one of twodata formats, either JSON or EJSON.
By default, endpoints return JSON, which is a standard data format thatis widely supported modern langauges and platforms. However, JSON cannotrepresent every data type that you can store in MongoDB and loses typeinformation for some data types.
You can also configure endpoints to return EJSON, which uses structuredJSON objects to fully represent the types that MongoDB supports. Thispreserves type information in responses but requires that yourapplication understands how to parse and use EJSON.
Tip
The official MongoDB drivers include methods for working with EJSON.You can also download a standalone parser likebson on npm.
{ "return_type":"JSON" }
{ "return_type":"EJSON" }
Access Permissions
The Data API uses your app'sdata access rules todetermine if a user can read and write data. To allow Data API requeststo access a specific collection, you must first define rules for thecollection.
You can also set up anIP Access List foradditional security.
API Versions
The Data API uses a built-in versioning scheme to upgrade endpoints overtime while maintaining backwards compatibility. Incoming requests canspecify which version of an endpoint to use in the request URL and theData API can serve any version that you have enabled.
You must enable a new version before users can call endpoints with thatversion. You can always enable the most recent Data API version.However, you cannot enable an older version after a newer version hasbeen released.
The following versions are currently supported:
betav1
Call a Data API Endpoint
You can call a Data API endpoint from any standard HTTP client. Eachrequest can include configuration headers and arguments in the requestbody.
HTTP/1.1 or greater is required when making requests.
Choose an API Version
Data API requests specify which version of the API to use in the requestURL. A request can specify any version that is enabled for your app.
https://data.mongodb-api.com/app/<App ID>/endpoint/data/<API Version>
Specify the Request Data Format
Data API requests must include aContent-Type header to specify thedata format used in the request body.
Use
Content-Type: application/jsonto represent standard JSON types in aData API request body.Use
Content-Type: application/ejsonto represent standard JSONtypesand additional EJSON types in a Data API request body.
curl -X GET \ https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/insertOne \ -H'apiKey: <API Key>' \ -H'Content-Type: application/ejson' \ -H'Accept: application/ejson' \ --data-raw'{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "hello", "document": { "_id": { "$oid": "629971c0d71aad65bd59c595" }, "greeting": "Hello, EJSON!", "date": { "$date": { "$numberLong": "1654589430998" } } } }'
{"insertedId":{"$oid":"629971c0d71aad65bd59c595"}}
curl -X POST \ https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/updateOne \ -H'apiKey: <API Key>' \ -H'Content-Type: application/json' \ --data-raw'{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "hello", "filter": { "greeting": "Hello, world!" }, "update": { "$set": { "greeting": "Hello, universe!" } } }'
{"matchedCount":1,"modifiedCount":1}
Choose a Response Data Format
A request can include anAccept header to request a specific dataformat for the response body, either JSON or EJSON. If a request doesnot include a validAccept header, the response uses the data formatspecified in yourData API configuration.
curl -X GET \ https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/findOne \ -H'apiKey: <API Key>' \ -H'Content-Type: application/json' \ -H'Accept: application/ejson' \ --data-raw'{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "hello", "projection": { "greeting": 1, "date": 1 } }'
{ "_id":{"$oid":"629971c0d71aad65bd59c545"}, "greeting":"Hello, Leafie!", "date":{"$date":{"$numberLong":"1654589430998"}} }
curl -X POST \ https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/findOne \ -H'apiKey: <API Key>' \ -H'Content-Type: application/json' \ -H'Accept: application/json' \ --data-raw'{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "hello", "projection": { "greeting": 1, "date": 1 } }'
{ "_id":"629971c0d71aad65bd59c545", "greeting":"Hello, Leafie!", "date":"2022-06-07T08:10:30.998Z" }
Authenticate the Request
If an endpoint is configured to use Application Authentication then youmust include a valid user access token or login credentials with everyrequest.
In general, bearer authentication with an access token has higherthroughput and is more secure than credential headers. Use an accesstoken instead of credential headers when possible. The token lets yourun multiple requests without re-authenticating the user. It also letsyou send requests from a web browser that enforcesCORS.
To use an access token, first authenticate the user through an AppServices authentication provider. Then, get the access token returnedfrom App Services and include it in the request's Authorization headerusing a Bearer token scheme. For more information on how to acquire anduse an access token, seeBearer Token Authentication.
curl -s"https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/findOne" \ -X POST \ -H"Accept: application/json" \ -H"Authorization: Bearer$ACCESS_TOKEN" \ -d'{ "dataSource": "mongodb-atlas", "database": "sample_mflix", "collection": "movies", "filter": { "title": "The Matrix" } }'
Alternatively, you can include valid login credentials for the user inthe request headers.
curl -s"https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/findOne" \ -X POST \ -H"Accept: application/json" \ -H"email: bob@example" \ -H"password: Pa55w0rd!" \ -d'{ "dataSource": "mongodb-atlas", "database": "sample_mflix", "collection": "movies", "filter": { "title": "The Matrix" } }'
curl -s"https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/findOne" \ -X POST \ -H"Accept: application/json" \ -H"apiKey: TpqAKQgvhZE4r6AOzpVydJ9a3tB1BLMrgDzLlBLbihKNDzSJWTAHMVbsMoIOpnM6" \ -d'{ "dataSource": "mongodb-atlas", "database": "sample_mflix", "collection": "movies", "filter": { "title": "The Matrix" } }'
curl -s"https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/findOne" \ -X POST \ -H"Accept: application/json" \ -H"jwtTokenString: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJteWFwcC1hYmNkZSIsInN1YiI6IjEyMzQ1Njc4OTAiLCJuYW1lIjoiSm9obiBEb2UiLCJleHAiOjIxNDU5MTY4MDB9.E4fSNtYc0t5XCTv3S8W89P9PKLftC4POLRZdN2zOICI" \ -d'{ "dataSource": "mongodb-atlas", "database": "sample_mflix", "collection": "movies", "filter": { "title": "The Matrix" } }'
Important
Don't Use API Keys in User-Facing Clients
If you're authenticating from a browser or another user-facing client application,avoid using an API key to log in. Instead, use another authenticationprovider that takes user-provided credentials. Never store API keys or othersensitive credentials locally.
Authorize the Request
Depending on your Data APIauthorization configuration, your requests may need to include additionalauthorization information.
All authenticated users are authorized to call the endpoint.Authenticated requests do not need to include authorizationinformation.
Authenticated users must prove that they are authorized to callthe endpoint by including the endpoint's secret string as thevalue of thesecret query parameter.
Example
The followingcurl request uses secret query parametervalidation with the secret string"12345":
curl -X POST \ https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/findOne?secret=12345 \ -H"Content-Type: application/json" \ -d'{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "filter": { "text": "Do the dishes" } }'
Authenticated users must prove that they are authorized to callthe endpoint by including anEndpoint-Signature header thatcontains a hexadecimal-encodedHMAC SHA-256 hash generated from the request bodyand the endpoint's secret string.
Endpoint-Signature: sha256=<hex encoded hash>
You could use the following function to generate the payloadsignature:
/** * Generate an HMAC request signature. *@param{string}secret - The secret validationstring, e.g. "12345" *@param{object}body - The endpoint requestbody e.g. { "message": "MESSAGE" } *@returns{string}The HMAC SHA-256 request signature inhex format. */ exports =functionsignEndpointRequest(secret, body) { const payload =EJSON.stringify(body); return utils.crypto.hmac(payload, secret,"sha256","hex"); };
Example
The followingcurl includes a payload signature headersigned with the secret value12345:
curl -X POST \ https://data.mongodb-api.com/app/myapp-abcde/endpoint/data/v1/action/findOne \ -H"Content-Type: application/json" \ -H"Endpoint-Signature: sha256=769cd86855787f476afc8b0d2cf9837ab0318181fca42f45f34b6dffd086dfc7" \ -d'{ "dataSource": "mongodb-atlas", "database": "learn-data-api", "collection": "tasks", "filter": { "text": "Do the dishes" } }'