Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

MongoDB Developer
Atlas
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
Atlaschevron-right

Calling the MongoDB Atlas Administration API: How to Do it from Node, Python, and Ruby

DJ Walker, Stanimira Vlaeva4 min read • Published Nov 30, 2021 • Updated Jun 18, 2024
Node.jsAtlasRubyPython
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
The real power of a cloud-hosted, fully managed service like MongoDB Atlas is that you can create whole new database deployment architectures automatically, using the services API. Getting to the MongoDB Atlas Administration API is relatively simple and, once unlocked, it opens up a massive opportunity to integrate and automate the management of database deployments from creation to deletion. The API itself is an extensive REST API. There's role-based access control and you can have user or app-specific credentials to access it.
There is one tiny thing that can trip people up though. The credentials have to be passed over using the digest authentication mechanism, not the more common basic authentication or using an issued token. Digest authentication, at its simplest, waits to get an HTTP 401 Unauthorized response from the web endpoint. That response comes with data and the client then sends an encrypted form of the username and password as a digest and the server works with that.
And that's why we’re here today: to show you how to do that with the least fuss in Python, Node, and Ruby. In each example, we'll try and access the base URL of the Atlas Administration API which returns a JSON document about the underlying applications name, build and other facts. You can find all code samples in the dedicated Github repository.

Setup

To use the Atlas Administration API, you need… a MongoDB Atlas account! If you don’t have one already, follow the Get Started with Atlas guide to create your account and first cluster.
The next requirement is the organization API key. You can set it up in two steps:
Create an API key in your Atlas organization. Make sure the key has the Organization Owner permission. Add your IP address to the API Access List for the API key.
Then, open a new terminal and export the following environment variables, where ATLAS_USER is your public key and ATLAS_USER_KEY is your private key.
1export ATLAS_USER=<public_key>
2export ATLAS_USER_KEY=<private_key>
You’re all set up! Let’s see how we can use the Admin API with Python, Node, and Ruby.

Python

We start with the simplest and most self-contained example: Python.
In the Python version, we lean on the requests library for most of the heavy lifting. We can install it with pip:
1python -m pip install requests
The implementation of the digest authentication itself is the following:
1import os
2import requests
3from requests.auth import HTTPDigestAuth
4import pprint
5
6base_url = "https://cloud.mongodb.com/api/atlas/v2/"
7auth = HTTPDigestAuth(
8 os.environ["ATLAS_USER"],
9 os.environ["ATLAS_USER_KEY"]
10)
11
12headers = {
13 'Accept': 'application/vnd.atlas.2023-01-01+json' # update date to desired API version
14}
15
16response = requests.get(base_url, auth = auth, headers=headers)
17pprint.pprint(response.json())
As well as importing requests, we also bring in HTTPDigestAuth from requests' auth module to handle digest authentication. The os import is just there so we can get the environment variables ATLAS_USER and ATLAS_USER_KEY as credentials. We also add a header to set the version of the Atlas Administration API that we want. The pprint import is just to format our results.
The critical part is the addition of auth = HTTPDigestAuth(...) to the requests.get() call. This installs the code needed to respond to the server when it asks for the digest.
If we now run this program...
Screenshot of the terminal emulator after the execution of the request script for Python. The printed message shows that the request was successful.
…we have our API response.

Node.js

For Node.js, we’ll take advantage of the urllib package which supports digest authentication.
1npm install urllib
The code for the Node.js HTTP request is the following:
1const urllib = require('urllib');
2const util = require('util');
3
4const baseUrl = 'https://cloud.mongodb.com/api/atlas/v2/';
5const { ATLAS_USER, ATLAS_USER_KEY } = process.env;
6const options = {
7 digestAuth: `${ATLAS_USER}:${ATLAS_USER_KEY}`,
8 headers: {
9 'Accept': 'application/vnd.atlas.2023-01-01+json' // update date to desired API version
10 }
11};
12
13urllib.request(baseUrl, options)
14 .then(({ data, res }) => {
15 if (res.statusCode !== 200) {
16 console.error(`Unexpected Status: ${res.statusCode}: ${res.statusText}`);
17 } else {
18 const jsonRes = JSON.parse(data);
19 console.log(util.inspect(jsonRes, { depth: null, colors: true }));
20 }
21 })
22 .catch(error => console.error('Error occurred:', error));
Taking it from the top… we first require and import the urllib package. Then, we extract the ATLAS_USER and ATLAS_USER_KEY variables from the process environment and use them to construct the authentication key. Then we add a header to set the version of the Atlas Administration API that we want. Finally, we send the request and handle the response in the passed callback.
And we’re ready to run:
Screenshot of the terminal emulator after the execution of the request script for Node.js. The printed message shows that the request was successful.
On to our final language...

Ruby

HTTParty is a widely used Gem which is used by the Ruby and Rails community to perform HTTP operations. It also, luckily, supports digest authentication. So, to get the party started:
1gem install httparty
There are two ways to use HTTParty. One is creating an object which abstracts the calls away while the other is just directly calling methods on HTTParty itself. For brevity, we'll do the latter. Here's the code:
1require 'httparty'
2require 'json'
3
4base_url = 'https://cloud.mongodb.com/api/atlas/v2/'
5options = {
6 :digest_auth => {
7 :username=>ENV['ATLAS_USER'],
8 :password=>ENV['ATLAS_USER_KEY']
9 },
10 headers: {
11 'Accept' => 'application/vnd.atlas.2023-01-01+json' # update date to desired API version
12 }
13}
14
15}
16
17result = HTTParty.get(base_url, options)
18
19pp JSON.parse(result.body())
We require the HTTParty and JSON gems first. We then create a dictionary with our username and key, mapped for HTTParty's authentication, and set a variable to hold the base URL. Finally we add a header to set the version of the Atlas Administration API that we want. We're ready to do our GET request now, and in the options (the second parameter of the GET request), we pass :digest_auth=>auth to switch on the digest support. We wrap up by JSON parsing the resulting body and pretty printing that. Put it all together and run it and we get:
Screenshot of the terminal emulator after the execution of the request script for Ruby. The printed message shows that the request was successful

Next Stop - The API

In this article, we learned how to call the MongoDB Atlas Administration API using digest authentication. We took advantage of the vast library ecosystems of Python, Node.js, and Ruby, and used the following open-source community libraries:
Requests for Python urllib for JavaScript httparty for Ruby
If your project requires it, you can implement digest authentication yourself by following the official specification. You can draw inspiration from the implementations in the aforementioned libraries.
Additionally, you can find all code samples from the article in Github.
With the authentication taken care of, just remember to be fastidious with your API key security and make sure you revoke unused keys. You can now move on to explore the API itself. Start in the documentation and see what you can automate today.

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Tutorial

Write A Serverless Function with AWS Lambda and MongoDB


Sep 23, 2022 | 15 min read
Tutorial

How to Use Custom Archival Rules and Partitioning on MongoDB Atlas Online Archive


May 31, 2023 | 5 min read
Tutorial

Add US Postal Abbreviations to Your Atlas Search in 5 Minutes


Sep 29, 2022 | 9 min read
Tutorial

How to Use Cohere Embeddings and Rerank Modules With MongoDB Atlas


Aug 14, 2024 | 10 min read
Table of Contents
  • Setup