Materials Project API
repository·main·Indexed 41 days ago
https://github.com/materialsproject/apiA Python-based interface and client (mp-api) for programmatically accessing and downloading data from the Materials Project database. It includes the ContribsClient for managing project metadata, querying contributions, and handling data components such as pymatgen structures, pandas DataFrames for tables, and file attachments.
What's inside Materials Project API
- The Materials Project API provides a programmatic interface to access the Materials Project database. This repository contains the core client implementation. For detailed instructions on how to use the API, query data, and download materials information, refer to the official documentation at https://docs.materialsproject.org/downloading-data/how-do-i-download-the-materials-project-database.
Get started with the mp-api client
mainThe
mp-apipackage provides the core client implementation for accessing the updated Materials Project API.This repository contains the low-level client classes and methods. For high-level guides, tutorials, and comprehensive instructions on how to use this code to download and query the Materials Project database, refer to the official Materials Project Next-Gen Documentation.
Data types for contribution components
mainWhen submitting or working with contributions, the client expects specific Python types for different components. If you are building contributions manually, ensure you use the correct types to avoid
MPContribsClientError:structures: Must use apymatgenStructureobject (orPmgStructure).tables: Must use apandas.DataFrameormp_api.client.contribs.Table.attachments: Must use astr(file path),pathlib.Path, ormp_api.client.contribs.Attachmentobject.
Use the document model for validated data
mainBy default, the client uses a
document_model(typically a PydanticBaseModel) to return data. This provides data validation and IDE auto-complete for available fields.If you prefer working with raw dictionaries and want to bypass validation overhead, set
use_document_model=Falseduring initialization.How CoreRester handles sub-resters
mainThe
CoreResterclass implements a lazy-loading pattern for sub-resters. Instead of initializing all API endpoints at once, sub-resters (likematerials,tasks, etc.) are only instantiated when they are first accessed as attributes.This allows the main client to remain lightweight while providing a seamless interface to various specialized API endpoints.
Configure the REST client via environment variables
mainTo simplify usage, especially for heavy users, you can set the
PMG_MAPI_KEYenvironment variable. When this variable is present, you can instantiate the client without passing anapi_keyargument explicitly.export PMG_MAPI_KEY="your_api_key_here" # Then in Python: from mp_api.client.core.client import MPRester mpr = MPRester()Initialize the Materials Project REST client
mainThe
_Resterclass (and its subclasses) serves as the base for interacting with the Materials Project REST API. You can initialize a client by providing anapi_key. If no key is provided, the client will automatically look for thePMG_MAPI_KEYenvironment variable.Key initialization arguments:
api_key: Your API key from the Materials Project dashboard.endpoint: The API URL (defaults tohttps://api.materialsproject.org).use_document_model: IfTrue(default), data is returned as validated Pydantic models. IfFalse, data is returned as raw dictionaries. Setting this toFalsebypasses data validation and auto-complete.local_dataset_cache: The directory where full datasets are cached (defaults tomp_datasetsin the user's home directory).force_renew: IfTrue, overwrites existing local datasets.timeout: Request timeout in seconds.
# Example initialization (assuming a subclass like MPRester is used) client = MPRester(api_key="YOUR_API_KEY") # Using the client as a context manager to ensure session closure with MPRester(api_key="YOUR_API_KEY") as mpr: # perform queries passGet support for mp-api
mainIf you encounter issues while using the
mp-apiclient, you can seek help through the following channels:- GitHub Issues: Report bugs or technical issues via GitHub Issues.
- MatSci Community: Engage with the community and ask questions on the MatSci community discourse.
Error: `MPContribsClientError`
mainThe
MPContribsClientErroris raised during contribution submission or downloading when validation fails. Common causes include:- Providing an incorrect type for a component (e.g., a string instead of a
Structurefor thestructurescomponent). - Providing an
includelist indownload_contributionsthat contains components not recognized byMPCC_SETTINGS.COMPONENTS. - Attempting to download a resource type that is not in the allowed list (must be one of
contributions,structures,tables, orattachments). - Providing an invalid format (must be
'json'or'csv'). - Duplicate detection: If
ignore_dupesisFalseand a duplicate MD5 digest is detected for a contribution.
- Providing an incorrect type for a component (e.g., a string instead of a
Retrieve contribution and component IDs
mainUse
get_all_idsto retrieve a list of existing contribution IDs and component (Object) IDs. This method supports two formats via thefmtargument:fmt="sets"(default): Returns a dictionary where each project maps to sets of IDs (e.g.,ids,identifiers, and component-specific sets likestructuresorattachments).fmt="map": Returns a dictionary mapping identifiers to their corresponding contribution data and component details.
Arguments:
include: A list of components to include in the response (e.g.,["structures", "tables"]).data_id_fields: A dictionary mapping projects to extra fields indatato be treated as ID fields.timeout: Timeout in seconds.
# Get sets of IDs ids_sets = client.get_all_ids(query={"project": "sandbox"}, include=["structures"], fmt="sets") # Get a map of identifiers to contribution data ids_map = client.get_all_ids(query={"project": "sandbox"}, include=["structures"], fmt="map")Get a single document by ID
mainThe
get_data_by_id()method retrieves a specific document using its primary key (e.g.,material_id,task_id).Note: This method is deprecated. It is recommended to use the
search()method instead by passing the ID as a keyword argument (e.g.,client.search(material_ids="mp-123")).Arguments:
document_id(str): The unique identifier for the document.fields(list[str] | None): A list of specific fields to return.
# Deprecated way doc = client.get_data_by_id("mp-123") # Recommended way docs = client.search(material_ids="mp-123") doc = docs[0] if docs else NoneRetrieve S3 data backed by DeltaTables
mainThe
_query_delta_backedmethod retrieves data from S3 that is structured as a DeltaTable. It handles local caching of the dataset to thelocal_dataset_cachedirectory.Arguments:
bucket: S3 OpenData bucket.prefix: S3 object prefix.access_controlled: Whether the table has access-controlled data (requires specific permissions).versioned: Whether the table is partitioned by database version.timeout: Timeout for getting access-controlled groups.label: A label for the table in theQueryBuilder.
Returns: A dictionary containing a
MPDatasetobject in thedatakey.