Skip to content
Official

Materials Research Starter Stack

Use the current Materials Project Python API to fetch a small material summary, preserve identifiers and units, and separate computed properties from experimental evidence.

Level: Intermediate Cost: Mixed Privacy: Depends on configuration ~30 min
Start Setup

You'll be able to

  • Query a specified Materials Project material with limited fields.
  • Preserve provenance, physical units and missing values.

What you'll build

Scope and access

Use Python 3.11 and mp-api 0.46.5 (package requirement >=3.11). A Materials Project account and its current API key are required. Use mp_api.client.MPRester rather than the legacy API client. Data retrieval uses an external authenticated service; this is not a fully offline workflow. This starter retrieves identified material summaries and provides a human review prompt; it does not automatically search all materials literature or predict experimentally measured values.

Scientific interpretation

The reference material is silicon mp-149, taken from the official API examples. Band gap is reported in eV and energy above hull in eV/atom. These depend on calculation methodology and database updates; no numerical band-gap baseline or experimental agreement is promised. Preserve missing values, retrieval date and material IDs. A stable flag is a database classification, not proof that a sample can be synthesized.

Materials data retrieval service

Materials Project API

Stack Components

Materials Project API

Materials data retrieval service · mp-api==0.46.5 / current MP API

Requires a private Materials Project API key; data and method-dependent values can change.

See upstream licenses and client/service account terms.

View Resource

Compatibility

ClientOSArchitectureVersion requirements
Python macOSAny>= 3.11
Python WindowsAny>= 3.11
Python LinuxAny>= 3.11

Setup & Test

1. Prepare the account and Python environment

All platforms

Install Python 3.11 and obtain your own API key from the Materials Project account dashboard. Confirm access to the current API. Keep the key out of source files, screenshots and shared logs.

Official source

Expected result

The account has a usable key stored privately.

2. Install isolated Python dependencies

macOS

Run in a new working directory. This shell variant applies to macOS/Linux; use the separate Windows step on Windows.

python3.11 -m venv .venv
.venv/bin/python -m pip install mp-api==0.46.5
.venv/bin/python -m pip freeze
Official source

Expected result

Packages install; record the resolved versions.

3. Install isolated Python dependencies

Linux

Run in a new working directory. This shell variant applies to macOS/Linux; use the separate Windows step on Windows.

python3.11 -m venv .venv
.venv/bin/python -m pip install mp-api==0.46.5
.venv/bin/python -m pip freeze
Official source

Expected result

Packages install; record the resolved versions.

4. Install Python dependencies on Windows

Windows

Use PowerShell and the virtual-environment interpreter directly.

py -3.11 -m venv .venv
.\.venv\Scripts\python.exe -m pip install mp-api==0.46.5
.\.venv\Scripts\python.exe -m pip freeze
Official source

Expected result

Packages install; record the resolved versions.

5. Set a private key on macOS/Linux

macOS

This bash command prompts silently and avoids putting the key value in the command text. Run the query from this same shell; clear the variable afterwards. From zsh, run bash first; keep the query in that bash session.

read -r -s -p "Materials Project API key: " MP_API_KEY
export MP_API_KEY
Official source

Expected result

MP_API_KEY is set in the query shell without printing its value.

6. Set a private key on Linux

Linux

Run in bash and use the same shell for the query. From zsh, run bash first; keep the query in that bash session.

read -r -s -p "Materials Project API key: " MP_API_KEY
export MP_API_KEY
Official source

Expected result

The environment variable is set without printing it.

7. Set a private key on Windows

Windows

Run in PowerShell. The value is necessarily available to the process environment; clear it after the query.

$atlasMpCredential = Read-Host "Materials Project API key" -AsSecureString
$env:MP_API_KEY = [System.Net.NetworkCredential]::new("", $atlasMpCredential).Password
Official source

Expected result

The query process can read MP_API_KEY; the value is not displayed.

8. Save the small summary query

All platforms

Save as materials_summary.py. It requests one specified material, writes a new file and never records the key in its result.

"""Fetch a small, identified Materials Project summary using a private API key.

Sources: https://docs.materialsproject.org/downloading-data/using-the-api/getting-started
         https://docs.materialsproject.org/downloading-data/using-the-api/examples
Source-reviewed example; not executed.
"""
import argparse
import json
import os
from datetime import datetime, timezone
from importlib.metadata import version
from pathlib import Path

from mp_api.client import MPRester


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--material-id", default="mp-149")
    parser.add_argument("--output", type=Path, default=Path("materials-summary.json"))
    args = parser.parse_args()
    api_key = os.environ.get("MP_API_KEY", "").strip()
    if not api_key:
        parser.error("Set MP_API_KEY privately; no request was sent.")
    if args.output.exists():
        parser.error("Choose a new output path; existing output will not be overwritten.")
    try:
        with MPRester(api_key) as mpr:
            docs = mpr.materials.summary.search(
                material_ids=[args.material_id],
                fields=["material_id", "formula_pretty", "band_gap", "energy_above_hull", "is_stable"],
                num_chunks=1,
                chunk_size=1,
            )
    except Exception:
        # Avoid including credential-bearing request details in shared output.
        parser.exit(1, "Materials Project request failed. Check key/account, network, rate limits and installed client version privately.\n")
    payload = {
        "retrieved_at": datetime.now(timezone.utc).isoformat(),
        "mp_api_version": version("mp-api"),
        "requested_material_id": args.material_id,
        "records": [
            {
                "material_id": str(doc.material_id),
                "formula": doc.formula_pretty,
                "band_gap_eV": doc.band_gap,
                "energy_above_hull_eV_per_atom": doc.energy_above_hull,
                "is_stable": doc.is_stable,
                "source_url": "https://materialsproject.org/materials/" + str(doc.material_id),
            }
            for doc in docs
        ],
    }
    with args.output.open("x", encoding="utf-8") as target:
        json.dump(payload, target, ensure_ascii=False, indent=2)
        target.write("\n")
    print("Saved", len(payload["records"]), "record(s) to", args.output)


if __name__ == "__main__":
    main()
Official source

Expected result

The script is saved beside .venv.

9. Retrieve the silicon example

All platforms

Run in the shell with the private key. On Windows use ..venv\Scripts\python.exe. Select a new output filename.

.venv/bin/python materials_summary.py --material-id mp-149 --output silicon-summary.json
Official source

Expected result

Actual JSON identifies mp-149 and formula Si, includes retrieval timestamp and client version, and keeps missing fields as null. Values come from the API; no particular band gap is required. If no record is returned, report it and inspect current database access rather than inventing data.

10. Review the material evidence

All platforms

Use as a human checklist, or provide only nonsecret returned data to an optional assistant. The API key must never be included.

Review the supplied silicon summary for mp-149. Preserve identifiers, timestamp, band-gap eV and energy-above-hull eV/atom units. Separate database calculations and stability classification from experimental measurements or synthesis claims. Keep null fields unavailable and cite the source URL.
Official source

Expected result

The review agrees with the returned data and its provenance.

11. Clear the private key after querying

Windows

Use unset MP_API_KEY in bash; in PowerShell use the displayed command.

Remove-Item Env:MP_API_KEY
Remove-Variable atlasMpCredential
Official source

Expected result

The temporary shell key is cleared.

Troubleshooting

  • Missing key: set MP_API_KEY in the same terminal that runs the script.
  • 401/403: check the current account key and API access privately; do not paste credentials into chat.
  • Client/schema conflict: use the isolated mp-api 0.46.5 environment and current MPRester docs.
  • Network/rate error: reduce query volume, retry with backoff and preserve already saved results.
  • No record: inspect the material ID and current database version.
  • Existing output: choose a new path.
  • Band gap differs from literature: inspect the calculation method rather than treating DFT and measured values as interchangeable.
Still not working

Alternatives

Use the Materials Project website for the same ID, or inspect its officially documented direct API. Literature comparison remains a separate, cited review step.