Menu Close Get Metabase

Working with the Metabase API

Sep 18, 2020 by The Metabase Team

This article gives an overview of the Metabase API.

Warning: the Metabase API can change

There are two caveats you should know before working with Metabase’s API:

  1. The API is subject to change. The API is tightly coupled with the frontend and is subject to change between releases. The endpoints likely won’t change that much (existing API endpoints are changed infrequently, and removed rarely), just know that if you write code to make use of the API, you might have to update some code in the future.
  2. The API is not versioned. Meaning: it can change version to version, so don’t expect to stay on a particular version of Metabase in order to use a “stable” API.

With that said, let’s see what you can do with the API, which is a lot.

Getting started with the Metabase API

To keep it simple, we’ll use the venerable command line utility, curl, for our API call examples, but you could also consider a dedicated tool for developing API requests (like Postman). To follow along, you can spin up a fresh local instance of Metabase and play around.

Authenticate your requests with a session token

You’ll need a session token to authenticate your requests, or Metabase will refuse to talk with you.

To get a session token, submit a request to the /api/session endpoint with your username and password, like so:

curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"username": "person@metabase.com", "password": "fakepassword"}' \
  http://localhost:3000/api/session

If you’re working with a remote server, you’ll need replace “localhost:3000” with your server address. This request will return a JSON object with a key called “id”, and the token as the key’s value, e.g.:

 {"id":"38f4939c-ad7f-4cbe-ae54-30946daf8593"}

You’ll need to include that session token in the headers of your subsequent requests, like so:

"X-Metabase-Session: 38f4939c-ad7f-4cbe-ae54-30946daf8593"

Some things to note about sessions:

  • By default, sessions are good for 14 days. You can configure this session duration by setting the environment variable MAX_SESSION_AGE (value is in minutes).
  • You should cache credentials to reuse them until they expire, because logins are rate-limited for security.
  • Invalid and expired session tokens return a 401 (Unauthorized) status code.
  • Handle 401 status codes gracefully. We recommend writing your code to fetch a new session token and automatically retry a request when the API returns a 401 status code.
  • Some endpoints require that the user be an admin, also known as a superuser. Endpoints that require admin or superuser status (admin = superuser) generally say so in their documentation. They will return a 403 (Forbidden) status code if the current user is not an admin.
  • If you would like an alternative authentication mechanism feel free to upvote this feature request.

Example GET request

Here’s an example API request (note the session token) that hits the /api/user/current endpoint, which returns information about the current user:

curl -X GET \
  -H "Content-Type: application/json" \
  -H "X-Metabase-Session: 38f4939c-ad7f-4cbe-ae54-30946daf8593" \
  http://localhost:3000/api/user/current

The above request returns a JSON object (formatted for readability):

 {
    "email": "person@metabase.com",
    "ldap_auth": false,
    "first_name": "Human",
    "locale": null,
    "last_login": "2020-08-31T13:08:50.203",
    "is_active": true,
    "is_qbnewb": false,
    "updated_at": "2020-08-31T13:08:50.203",
    "group_ids": [
        1,
        2
    ],
    "is_superuser": true,
    "login_attributes": null,
    "id": 1,
    "last_name": "Person",
    "date_joined": "2020-08-19T10:50:46.547",
    "personal_collection_id": 1,
    "common_name": "Human Person",
    "google_auth": false
}

Example POST request

You can also use a file to store the JSON payload for a POST request. This makes it easy to have a pre-defined set of requests you want to make to the API.

curl -H @header_file.txt -d @payload.json http://localhost/api/card

Here’s an example of a JSON file (the @payload.json in the command above) that creates a question:

{
  "visualization_settings": {
    "table.pivot_column": "QUANTITY",
    "table.cell_column": "SUBTOTAL"
  },
  "description value": "A card generated by the API",
  "collection_position": null,
  "result_metadata": null,
  "metadata_checksum": null,
  "collection_id": null,
  "name": "API-generated question",
  "dataset_query": {
    "database": 1,
    "query": {
      "source-table": 2
    },
    "type": "query"
  },
  "display": "table"
}

That request generated the question shown in Figure 1.

Figure 1. A question in Metabase generated by the API: a list of the <strong>Orders</strong> table in the <strong>Sample Dataset</strong>
Figure 1. A question in Metabase generated by the API: a list of the Orders table in the Sample Dataset

Use developer tools to see how Metabase makes requests

If the auto-generated API docs are unclear, you can use the developer tools that ship with browsers like Firefox, Chrome, and Edge to view the requests and responses Metabase makes (see figure 2).

Figure 2. Using Firefox's network tab to inspect the JSON request payload that Metabase sent when a user clicked to save a question created in the notebook editor.
Figure 2. Using Firefox's network tab to inspect the JSON request payload that Metabase sent when a user clicked to save a question created in the notebook editor.

In the Metabase application, perform the action that you’d like to script using the API, such as adding a user or creating a dashboard. Then use the developer tools in your browser to view the request Metabase made to the server when you performed that action.

A few things you can do with the Metabase API

Provision a Metabase instance

In addition to using environment variables, you can use the Metabase API to setup an instance of Metabase. Once you have installed Metabase using your preferred method, and the Metabase server is up and running, you can create the first user (as an Admin) by posting to a special endpoint, /api/setup. This /api/setup endpoint:

  • Creates the first user as an Admin (superuser).
  • Logs them in.
  • Returns a session ID.

You can then configure settings using the /api/settings endpoint, set up email using the /api/email endpoint, and use the /api/setup/admin_checklist endpoint to verify your setup progress. See figure 3 for the graphical representation of the checklist in the Admin panel.

Figure 3. Admin checklist for setting up Metabase to make the most of your application.
Figure 3. Admin checklist for setting up Metabase to make the most of your application.

Add a data source

You can add a new database using the POST /api/database/ endpoint, and validate that database’s connection details using the /api/setup/validate endpoint.

Once you’ve connected the database to your Metabase instance, you can rescan the database’s field values and update the schema metadata,

You can even add our trusty Sample Dataset as a new database to your instance with POST /api/database/sample_dataset.

Here’s an example database creation call for a Redshift database.

curl -s -X POST \
    -H "Content-type: application/json" \
    -H "X-Metabase-Session: ${MB_TOKEN}" \
    http://localhost:3000/api/database \
    -d '{
        "engine": "redshift",
        "name": "Redshift",
        "details": {
            "host": "redshift.aws.com",
            "port": "5432",
            "db": "dev",
            "user": "root",
            "password": "password"
        }
    }'

Set up users, groups, and permissions

You can use the /api/user endpoints to create, update, and disable users, and use the /api/permissions endpoints to set up groups, and add users to those groups.

Here’s an example curl command to create a user:

curl -s "http://localhost:3000/api/user" \
    -H 'Content-Type: application/json' \
    -H "X-Metabase-Session: ${MB_TOKEN}" \
    -d '{
    "first_name":"Basic",
    "last_name":"User",
    "email":"basic@somewhere.com",
    "password":"Sup3rS3cure_:}"
}'

Generate reports

In Metabase, “reports” are referred to as Dashboards. You can interact with dashboards using the /api/dashboard endpoint. You can create a new dashboard with POST /api/dashboard/, and add a saved question to a dashboard with POST/api/dashboard/:id/cards

Useful endpoints

Note that the links in the Endpoint column below will take you to you to the first action available for that endpoint, which alphabetically is usually the DELETE action. You can scroll down in the API documentation to see the full list of actions and URLs for that endpoint, and view descriptions of each.

Domain Description Endpoint
Collections Collections are a great way to organize your dashboards, saved questions, and pulses. /api/collection
Dashboards Dashboards are reports that comprise a set of questions and text cards. /api/dashboard
Databases Fetch databases, fields, schemas, primary (entity) keys, lists of tables, and more. /api/database
Email Update emails settings and send test emails. /api/email
Embedding Use signed JWTs to fetch info on embedded cards and dashboards. /api/embed
Metrics Metrics are saved computations (like Revenue). Create and update metrics, return related entities, revert to prior versions, and more. /api/metric
Permissions Metabase manages permissions to databases and collections with groups. Create permission groups, add and remove users to groups, retrieve a graph of all permissions groups, and more. /api/permissions
Search Search cards (questions), dashboards, collections and pulses for a substring. /api/search
Segments Segments are named sets of filters (like “Active Users”). Create and update segments, revert to previous versions, and more. /api/segment
Sessions Reset passowrds with tokens, login with Google Auth, send passord reset emails, and more. /api/sessions
Settings Create/update global application settings. /api/setting
Queries Use the API to execute queries and return their results in a specified format. /api/dataset
Questions Questions (known as cards in the API) are queries and their visualized results. /api/card

There are some other cool endpoints to check out, like api/database/:virtual-db/metadata, which is used to “fool” the frontend so that it can treat Saved Questions as if they were tables in a virtual database, which is how Metabase allows you to use Saved Questions as if they were data sources.

Here is a complete list of API endpoints along with documentation for each endpoint, so dig around and see what other cool endpoints you can find.

The endpoint reference is periodically updated with new versions of Metabase. You can also generate the reference by running:

java -jar metabase.jar api-documentation

Running Custom Queries

Queries are written in our custom JSON-based query language, MBQL. You can view the definitive grammar for MBQL, as well as an (incomplete) MBQL reference document to learn about some of the design philosophy behind MBQL.

To familiarize yourself with MBQL, we recommend using the Metabase application to build a custom question, then use your browser’s developer tools to see how Metabase formatted the request body with the query.

Have fun

Spin up a local instance of Metabase, experiment with the API, and have fun! If you get stuck, check out our forum to see if anyone’s run into a similar issue, or post a new question.