Skip to content

API Reference

This API reference describes the Python interface to the ASI-SSDC SED Builder service. The package provides functions to build spectral energy distributions (SEDs) for astronomical sources by querying data from multi-frequency catalogs and converting them into various output formats.

Note

At present, only internally hosted catalogs are supported. More will come.

Functions

get_data(*args, name=None, ra=None, dec=None, catalog_ids=tuple(), timeout=30.0)

get_data(
    *args: Never,
    ra: float,
    dec: float,
    catalog_ids: Sequence[int] = tuple(),
    timeout: float = ...
) -> GetDataResponse
get_data(
    *args: Never,
    name: str,
    catalog_ids: Sequence[int] = tuple(),
    timeout: float = ...
) -> GetDataResponse

Queries the SSDC SED Builder API to retrieve Spectral Energy Distribution data for the specified sky coordinates or source name.

Parameters:

Name Type Description Default
ra float

Right ascension in degrees (0 to 360). Mutually exclusive with name.

None
dec float

Declination in degrees (-90 to 90). Mutually exclusive with name.

None
name str

Source name to resolve to coordinates. Tried against SSDC, SIMBAD, NED, and finally astropy's CDS/Sesame resolver.

None
catalog_ids Sequence[int]

A sequence of catalog ids to query from (see Notes). By default fetches from all catalogs.

tuple()
timeout float

Request timeout in seconds (default: 30.0).

30.0

Returns:

Type Description
GetDataResponse

A response object. Use its methods to recover data in different formats.

Raises:

Type Description
ValueError

If arguments are invalid or conflicting.

ValidationError

If coordinates are out of valid range.

TimeoutError

If the API request exceeds the timeout.

RuntimeError

If the API request fails for other reasons.

Example
from sedbuilder import get_data

# By coordinates
response = get_data(ra=194.04625, dec=-5.789167)
# By name
response = get_data(name="Crab Nebula")

# Access data in different formats
table = response.to_astropy()     # Astropy Table
data_dict = response.to_dict()    # Python dictionary
jt = response.to_jetset(z=0.034)  # Jetset table
json_str = response.to_json()     # JSON string
df = response.to_pandas()         # Pandas DataFrame (requires pandas)
Note

You can find available catalogs and their ids with catalogs.

Source code in sedbuilder/requests.py
def get_data(
    *args,
    name: str = None,
    ra: float = None,
    dec: float = None,
    catalog_ids: Sequence[int] = tuple(),
    timeout: float = 30.0,
) -> GetDataResponse:
    """Queries the SSDC SED Builder API to retrieve Spectral Energy Distribution
    data for the specified sky coordinates or source name.

    Args:
        ra: Right ascension in degrees (0 to 360). Mutually exclusive with `name`.
        dec: Declination in degrees (-90 to 90). Mutually exclusive with `name`.
        name: Source name to resolve to coordinates. Tried against SSDC, SIMBAD,
            NED, and finally astropy's CDS/Sesame resolver.
        catalog_ids: A sequence of catalog ids to query from (see Notes). By default
            fetches from all catalogs.
        timeout: Request timeout in seconds (default: 30.0).

    Returns:
        A response object. Use its methods to recover data in different formats.

    Raises:
        ValueError: If arguments are invalid or conflicting.
        ValidationError: If coordinates are out of valid range.
        TimeoutError: If the API request exceeds the timeout.
        RuntimeError: If the API request fails for other reasons.

    Example:
        ```python
        from sedbuilder import get_data

        # By coordinates
        response = get_data(ra=194.04625, dec=-5.789167)
        # By name
        response = get_data(name="Crab Nebula")

        # Access data in different formats
        table = response.to_astropy()     # Astropy Table
        data_dict = response.to_dict()    # Python dictionary
        jt = response.to_jetset(z=0.034)  # Jetset table
        json_str = response.to_json()     # JSON string
        df = response.to_pandas()         # Pandas DataFrame (requires pandas)
        ```

    Note:
        You can find available catalogs and their ids with [`catalogs`][sedbuilder.requests.catalogs].
    """
    if args:
        raise TypeError(
            "Are you trying to call `get_data` with a positional argument? "
            "get_data() accepts keyword arguments only. "
            f"Hint: get_data(name='Crab Nebula'); get_data(ra=194.04, dec=-5.78)."
        )
    if name is not None and ((ra is None) and (dec is None)):
        # we are calling _resolve_name leaving its default timeout
        # this is to avoid waiting too long for just the name resolver
        # if we get delayed by the exponential rate meter
        (ra, dec), _ = resolve_name(name)
        return _get_data_coords(ra=ra, dec=dec, catalog_ids=catalog_ids, timeout=timeout)
    if name is None and ((ra is not None) and (dec is not None)):
        return _get_data_coords(ra=ra, dec=dec, catalog_ids=catalog_ids, timeout=timeout)
    # catches missing args, partial coordinates or mixed name/coordinates queries
    raise ValueError("Provide either 'name' or both 'ra' and 'dec'.")

get_data_from_json(filepath)

Reads a JSON file containing SED Builder API response data and validates it against get_data response schema.

Parameters:

Name Type Description Default
filepath FilePath

Path to a JSON file containing SED Builder response data. The file must exist and contain valid JSON matching the get_data response schema.

required

Returns:

Type Description
GetDataResponse

Response object with validated SED data.

Raises:

Type Description
ValidationError

If the file does not exist, or if file content does not match the expected response schema.

Source code in sedbuilder/utils.py
@validate_call
def get_data_from_json(
    filepath: FilePath,
) -> GetDataResponse:
    """Reads a JSON file containing SED Builder API response data and validates it
    against `get_data` response schema.

    Args:
        filepath: Path to a JSON file containing SED Builder response data.
                  The file must exist and contain valid JSON matching the `get_data`
                  response schema.

    Returns:
        Response object with validated SED data.

    Raises:
        ValidationError: If the file does not exist, or if file content does not
                         match the expected response schema.
    """
    return GetDataResponse.model_validate_json(Path(filepath).read_text())

catalogs(timeout=30.0)

Queries the SSDC SED Builder API to retrieve the list of available catalogs.

Parameters:

Name Type Description Default
timeout Annotated[float | int, Field(gt=0.0, description='Request timeout in seconds.')]

Request timeout in seconds (default: 30.0).

30.0

Returns:

Type Description
CatalogsResponse

A response object containing catalog information. Use its methods to recover data in different formats.

Raises:

Type Description
TimeoutError

If the API request exceeds the timeout.

RuntimeError

If the API request fails for other reasons.

Example
from sedbuilder import catalogs

# Get list of available catalogs
response = catalogs()

# Access catalog data as a list of dictionaries
catalog_list = response.to_list()
Source code in sedbuilder/requests.py
@validate_call
def catalogs(
    timeout: Annotated[
        float | int,
        Field(gt=0.0, description="Request timeout in seconds."),
    ] = 30.0,
) -> CatalogsResponse:
    """Queries the SSDC SED Builder API to retrieve the list of available catalogs.

    Args:
        timeout: Request timeout in seconds (default: 30.0).

    Returns:
        A response object containing catalog information. Use its methods to recover data in different formats.

    Raises:
        TimeoutError: If the API request exceeds the timeout.
        RuntimeError: If the API request fails for other reasons.

    Example:
        ```python
        from sedbuilder import catalogs

        # Get list of available catalogs
        response = catalogs()

        # Access catalog data as a list of dictionaries
        catalog_list = response.to_list()
        ```
    """
    r = _get_and_validate(APIPaths.CATALOGS(), timeout)
    return CatalogsResponse(**r.json())

catalogs_from_json(filepath)

Reads a JSON file containing SED Builder API catalog data and validates it against catalogs response schema.

Parameters:

Name Type Description Default
filepath FilePath

Path to a JSON file containing SED Builder catalog data. The file must exist and contain valid JSON matching the catalogs response schema.

required

Returns:

Type Description
CatalogsResponse

Response object with validated catalog information.

Raises:

Type Description
ValidationError

If the file does not exist, or if file content does not match the expected response schema.

Source code in sedbuilder/utils.py
@validate_call
def catalogs_from_json(
    filepath: FilePath,
) -> CatalogsResponse:
    """Reads a JSON file containing SED Builder API catalog data and validates it
    against `catalogs` response schema.

    Args:
        filepath: Path to a JSON file containing SED Builder catalog data.
                  The file must exist and contain valid JSON matching the `catalogs`
                  response schema.

    Returns:
        Response object with validated catalog information.

    Raises:
        ValidationError: If the file does not exist, or if file content does not
                         match the expected response schema.
    """
    return CatalogsResponse.model_validate_json(Path(filepath).read_text())

resolve_name(name, timeout=2.0)

Resolve a source name to (ra, dec) via SSDC name resolver, with astropy fallback.

Queries the SSDC server — which checks SSDC, SIMBAD, and NED — falling back to the CDS Sesame resolver via astropy if no match is found.

Parameters:

Name Type Description Default
name str

Source name to resolve.

required
timeout Annotated[float, Field(gt=0.0)]

Timeout in seconds for the SSDC request. Defaults to 2.0.

2.0

Returns:

Type Description
tuple[float, float]

The source (ra, dec) tuple, in degrees.

str

str containing the name of the DB resolving the call.

Raises:

Type Description
RuntimeError

If no resolver can identify the source.

Example
from sedbuilder import resolve_name

(ra, dec), db = resolve_name("Crab Nebula")
Source code in sedbuilder/requests.py
@validate_call
def resolve_name(
    name: str,
    timeout: Annotated[float, Field(gt=0.0)] = 2.0,
) -> tuple[tuple[float, float], str]:
    """Resolve a source name to (ra, dec) via SSDC name resolver, with astropy fallback.

    Queries the SSDC server — which checks SSDC, SIMBAD, and NED — falling back to the CDS Sesame resolver via astropy if no match is found.

    Args:
        name: Source name to resolve.
        timeout: Timeout in seconds for the SSDC request. Defaults to 2.0.

    Returns:
        The source `(ra, dec)` tuple, in degrees.
        `str` containing the name of the DB resolving the call.

    Raises:
        RuntimeError: If no resolver can identify the source.

    Example:
        ```python
        from sedbuilder import resolve_name

        (ra, dec), db = resolve_name("Crab Nebula")
        ```
    """
    try:
        r = _get_and_validate(APIPaths.NAME_RESOLVER(name=name, ssdc=True, simbad=True, ned=True), timeout)
        response = NameResolverResponse(**r.json())
    except (TimeoutError, RuntimeError):
        response = NameResolverResponse(results=[])
    if response.results:
        item = min(response.results, key=lambda item: _DB_PRIORITY[item.db])
        ra, dec = item.ra, item.dec
        source = item.db
    else:
        coords = _resolve_name_astropy(name)
        if coords is None:
            raise RuntimeError(f"Cannot resolve source {name!r}.")
        ra, dec = coords
        source = "astropy"
    _log.info("Resolved %r → ra=%.6f, dec=%.6f (via %s)", name, ra, dec, source)
    return (ra, dec), source

Classes

GetDataResponse

Bases: BaseModel

SED Builder API response to getData endpoint.

To retrieve data you call .to_astropy(), or .to_dict() and other methods.

Attributes:

Name Type Description
response_info ResponseInfo

Status information about the API response.

properties Properties

Additional science properties for the queried source.

datasets list[Dataset]

List of catalog entries with measurements.

meta Meta

Metadata about the response format and other non-science info.

Source code in sedbuilder/schemas.py
class GetDataResponse(BaseModel):
    """SED Builder API response to `getData` endpoint.

    To retrieve data you call `.to_astropy()`, or `.to_dict()` and other methods.

    Attributes:
        response_info: Status information about the API response.
        properties: Additional science properties for the queried source.
        datasets: List of catalog entries with measurements.
        meta: Metadata about the response format and other non-science info.
    """

    response_info: ResponseInfo = Field(alias="ResponseInfo")
    properties: Properties = Field(alias="Properties")
    datasets: list[Dataset] = Field(alias="Datasets")
    meta: Meta = Field(alias="Meta")

    def __repr__(self) -> str:
        return f"Response(status={self.response_info.status_code!r}, " f"datasets: [#{len(self.datasets)} entries])"

    def is_successful(self) -> bool:
        """Check if the API response indicates success.

        Returns:
            True if the response status code is 'OK'.
        """
        return self.response_info.status_code == "OK"

    def to_dict(self) -> dict:
        """Converts data to a dictionary.

        Returns:
            A dictionary from the response JSON.
        """
        return self.model_dump()

    def to_json(self) -> str:
        """Converts data to JSON.

        Returns:
            A JSON string.
        """
        return json.dumps(self.model_dump())

    def to_pandas(self) -> Any:
        """Converts data to a pandas DataFrame.

        Requires pandas to be installed. Install with `pip install pandas`.

        Returns:
            A pandas dataframe.

        Raises:
            ImportError: If pandas is not installed.
        """
        try:
            return self.to_astropy().to_pandas()
        except ImportError:
            raise ImportError("pandas is required for this method. Install it with: pip install pandas")

    def to_astropy(self) -> Table:
        """Convert data to an astropy Table.

        Returns:
            Astropy Table with one row per measurements.
        """
        # the gist of it is to build two different tables and to stack them horizontally.
        # the first table is for data columns, the second for the catalog columns.
        columns_data = [*TABLE_SCHEMA.columns(kind="data")]
        columns_source = [*TABLE_SCHEMA.columns(kind="source")]

        # first we have to unpack the data
        rows_data, rows_source = [], []
        for dataset in self.datasets:
            _dsmp = dataset.source.model_dump()
            source_dump = {col.name: _dsmp[col.field] for col in columns_source if col.field in _dsmp}
            for source_data in dataset.data:
                rows_data.append(source_data.model_dump())
                rows_source.append(source_dump)

        # first, the column table
        table_data = Table(
            rows_data,
            names=[col.name for col in columns_data],
            dtype=[col.dtype for col in columns_data],
            units=[col.units for col in columns_data],
        )

        # second, the catalog property table
        table_source = Table(
            rows_source,
            names=[col.name for col in columns_source],
            dtype=[col.dtype for col in columns_source],
            units=[col.units for col in columns_source],
        )

        # then, we stack
        table = hstack((table_data, table_source))

        # and add metadata
        for m in TABLE_SCHEMA.metadata():
            table.meta[m.name] = getattr(self.properties, m.name)
            if m.units:
                table.meta[m.name] *= m.units
        return table

    @validate_call
    def to_jetset(
        self,
        z: Annotated[float, Field(ge=0.0)],
        ul_cl: Annotated[float, Field(ge=0.0, le=1.0)] = 0.95,
        restframe: Literal["obs", "src"] = "obs",
        data_scale: Literal["lin-lin", "log-log"] = "lin-lin",
        obj_name: str = "new-src",
    ) -> Table:
        # noinspection PyUnresolvedReferences
        """Convert data to Jetset format.

        The output includes both the data table with renamed columns and appropriate units,
        plus metadata needed for Jetset analysis.

        Args:
            z: Source redshift, must be greater or equal to 0.
            ul_cl: Confidence level for upper limits, must be between 0 and 1,
                exclusive. Default is 0.95.
            restframe: Reference frame for the data. Options are "obs" for observed flux (default)
                and "src" for source luminosities.
            data_scale: Scale format of the data. Options are  "lin-lin" for linear scale (default),
                and "log-log" for logarithmic scale.
            obj_name: Name identifier for the object. Default is "new-src".

        Returns:
            A table with column names, units and metadata, compatible with `jetset.data_loader.Data`.

        Raises:
            ValueError: If z < 0, ul_cl is not in (0, 1), restframe or data_scale
                have invalid values, obj_name is empty, or required table columns
                are missing.

        Example:
            ```python
            from sedbuilder import get_data
            from jetset.data_loader import Data

            # Get response from SED for astronomical coordinates
            response = get_data(ra=194.04625, dec=-5.789167)
            # Initialize jetset data structure
            jetset_data = Data(response.to_jetset(z=0.034))
            ```
        """

        def info2ul(infos: Column) -> list[bool]:
            """Parses info column and checks where it contains 'Upper Limit' tag.'"""
            return ["Upper Limit" in [i.strip() for i in str(info).split(self.meta.info_separator)] for info in infos]

        # type and label choice from Jetset documentation, "Data format and SED data".
        # fmt: off
        t = self.to_astropy()
        table = Table()
        table.add_column(t[TABLE_SCHEMA.FREQUENCY.name].astype(np.float64), name="x")
        table.add_column(t[TABLE_SCHEMA.FREQUENCY_ERROR.name].astype(np.float64), name="dx")
        table.add_column(t[TABLE_SCHEMA.NUFNU.name].astype(np.float64), name="y")
        table.add_column(t[TABLE_SCHEMA.NUFNU_ERROR.name].astype(np.float64), name="dy")
        table.add_column(np.nan_to_num(t[TABLE_SCHEMA.START_TIME.name].value, nan=0.0).astype(np.float64), name="T_start")
        table.add_column(np.nan_to_num(t[TABLE_SCHEMA.STOP_TIME.name].value, nan=0.0).astype(np.float64), name="T_stop")
        table.add_column(info2ul(t[TABLE_SCHEMA.INFO.name]), name="UL")
        table.add_column(t[TABLE_SCHEMA.SOURCE_NAME.name].astype(str), name="dataset")
        table.meta["z"] = z
        table.meta["UL_CL"] = ul_cl
        table.meta["restframe"] = restframe
        table.meta["data_scale"] = data_scale
        table.meta["obj_name"] = obj_name
        # fmt: on
        return table

    def sources(self) -> list[dict]:
        """Returns a list of references to the catalog and papers from which the data is collected.

        Returns:
            Datasets source metadata.
        """
        return [d.source.model_dump() for d in self.datasets]

is_successful()

Check if the API response indicates success.

Returns:

Type Description
bool

True if the response status code is 'OK'.

Source code in sedbuilder/schemas.py
def is_successful(self) -> bool:
    """Check if the API response indicates success.

    Returns:
        True if the response status code is 'OK'.
    """
    return self.response_info.status_code == "OK"

sources()

Returns a list of references to the catalog and papers from which the data is collected.

Returns:

Type Description
list[dict]

Datasets source metadata.

Source code in sedbuilder/schemas.py
def sources(self) -> list[dict]:
    """Returns a list of references to the catalog and papers from which the data is collected.

    Returns:
        Datasets source metadata.
    """
    return [d.source.model_dump() for d in self.datasets]

to_astropy()

Convert data to an astropy Table.

Returns:

Type Description
Table

Astropy Table with one row per measurements.

Source code in sedbuilder/schemas.py
def to_astropy(self) -> Table:
    """Convert data to an astropy Table.

    Returns:
        Astropy Table with one row per measurements.
    """
    # the gist of it is to build two different tables and to stack them horizontally.
    # the first table is for data columns, the second for the catalog columns.
    columns_data = [*TABLE_SCHEMA.columns(kind="data")]
    columns_source = [*TABLE_SCHEMA.columns(kind="source")]

    # first we have to unpack the data
    rows_data, rows_source = [], []
    for dataset in self.datasets:
        _dsmp = dataset.source.model_dump()
        source_dump = {col.name: _dsmp[col.field] for col in columns_source if col.field in _dsmp}
        for source_data in dataset.data:
            rows_data.append(source_data.model_dump())
            rows_source.append(source_dump)

    # first, the column table
    table_data = Table(
        rows_data,
        names=[col.name for col in columns_data],
        dtype=[col.dtype for col in columns_data],
        units=[col.units for col in columns_data],
    )

    # second, the catalog property table
    table_source = Table(
        rows_source,
        names=[col.name for col in columns_source],
        dtype=[col.dtype for col in columns_source],
        units=[col.units for col in columns_source],
    )

    # then, we stack
    table = hstack((table_data, table_source))

    # and add metadata
    for m in TABLE_SCHEMA.metadata():
        table.meta[m.name] = getattr(self.properties, m.name)
        if m.units:
            table.meta[m.name] *= m.units
    return table

to_dict()

Converts data to a dictionary.

Returns:

Type Description
dict

A dictionary from the response JSON.

Source code in sedbuilder/schemas.py
def to_dict(self) -> dict:
    """Converts data to a dictionary.

    Returns:
        A dictionary from the response JSON.
    """
    return self.model_dump()

to_jetset(z, ul_cl=0.95, restframe='obs', data_scale='lin-lin', obj_name='new-src')

Convert data to Jetset format.

The output includes both the data table with renamed columns and appropriate units, plus metadata needed for Jetset analysis.

Parameters:

Name Type Description Default
z Annotated[float, Field(ge=0.0)]

Source redshift, must be greater or equal to 0.

required
ul_cl Annotated[float, Field(ge=0.0, le=1.0)]

Confidence level for upper limits, must be between 0 and 1, exclusive. Default is 0.95.

0.95
restframe Literal['obs', 'src']

Reference frame for the data. Options are "obs" for observed flux (default) and "src" for source luminosities.

'obs'
data_scale Literal['lin-lin', 'log-log']

Scale format of the data. Options are "lin-lin" for linear scale (default), and "log-log" for logarithmic scale.

'lin-lin'
obj_name str

Name identifier for the object. Default is "new-src".

'new-src'

Returns:

Type Description
Table

A table with column names, units and metadata, compatible with jetset.data_loader.Data.

Raises:

Type Description
ValueError

If z < 0, ul_cl is not in (0, 1), restframe or data_scale have invalid values, obj_name is empty, or required table columns are missing.

Example
from sedbuilder import get_data
from jetset.data_loader import Data

# Get response from SED for astronomical coordinates
response = get_data(ra=194.04625, dec=-5.789167)
# Initialize jetset data structure
jetset_data = Data(response.to_jetset(z=0.034))
Source code in sedbuilder/schemas.py
@validate_call
def to_jetset(
    self,
    z: Annotated[float, Field(ge=0.0)],
    ul_cl: Annotated[float, Field(ge=0.0, le=1.0)] = 0.95,
    restframe: Literal["obs", "src"] = "obs",
    data_scale: Literal["lin-lin", "log-log"] = "lin-lin",
    obj_name: str = "new-src",
) -> Table:
    # noinspection PyUnresolvedReferences
    """Convert data to Jetset format.

    The output includes both the data table with renamed columns and appropriate units,
    plus metadata needed for Jetset analysis.

    Args:
        z: Source redshift, must be greater or equal to 0.
        ul_cl: Confidence level for upper limits, must be between 0 and 1,
            exclusive. Default is 0.95.
        restframe: Reference frame for the data. Options are "obs" for observed flux (default)
            and "src" for source luminosities.
        data_scale: Scale format of the data. Options are  "lin-lin" for linear scale (default),
            and "log-log" for logarithmic scale.
        obj_name: Name identifier for the object. Default is "new-src".

    Returns:
        A table with column names, units and metadata, compatible with `jetset.data_loader.Data`.

    Raises:
        ValueError: If z < 0, ul_cl is not in (0, 1), restframe or data_scale
            have invalid values, obj_name is empty, or required table columns
            are missing.

    Example:
        ```python
        from sedbuilder import get_data
        from jetset.data_loader import Data

        # Get response from SED for astronomical coordinates
        response = get_data(ra=194.04625, dec=-5.789167)
        # Initialize jetset data structure
        jetset_data = Data(response.to_jetset(z=0.034))
        ```
    """

    def info2ul(infos: Column) -> list[bool]:
        """Parses info column and checks where it contains 'Upper Limit' tag.'"""
        return ["Upper Limit" in [i.strip() for i in str(info).split(self.meta.info_separator)] for info in infos]

    # type and label choice from Jetset documentation, "Data format and SED data".
    # fmt: off
    t = self.to_astropy()
    table = Table()
    table.add_column(t[TABLE_SCHEMA.FREQUENCY.name].astype(np.float64), name="x")
    table.add_column(t[TABLE_SCHEMA.FREQUENCY_ERROR.name].astype(np.float64), name="dx")
    table.add_column(t[TABLE_SCHEMA.NUFNU.name].astype(np.float64), name="y")
    table.add_column(t[TABLE_SCHEMA.NUFNU_ERROR.name].astype(np.float64), name="dy")
    table.add_column(np.nan_to_num(t[TABLE_SCHEMA.START_TIME.name].value, nan=0.0).astype(np.float64), name="T_start")
    table.add_column(np.nan_to_num(t[TABLE_SCHEMA.STOP_TIME.name].value, nan=0.0).astype(np.float64), name="T_stop")
    table.add_column(info2ul(t[TABLE_SCHEMA.INFO.name]), name="UL")
    table.add_column(t[TABLE_SCHEMA.SOURCE_NAME.name].astype(str), name="dataset")
    table.meta["z"] = z
    table.meta["UL_CL"] = ul_cl
    table.meta["restframe"] = restframe
    table.meta["data_scale"] = data_scale
    table.meta["obj_name"] = obj_name
    # fmt: on
    return table

to_json()

Converts data to JSON.

Returns:

Type Description
str

A JSON string.

Source code in sedbuilder/schemas.py
def to_json(self) -> str:
    """Converts data to JSON.

    Returns:
        A JSON string.
    """
    return json.dumps(self.model_dump())

to_pandas()

Converts data to a pandas DataFrame.

Requires pandas to be installed. Install with pip install pandas.

Returns:

Type Description
Any

A pandas dataframe.

Raises:

Type Description
ImportError

If pandas is not installed.

Source code in sedbuilder/schemas.py
def to_pandas(self) -> Any:
    """Converts data to a pandas DataFrame.

    Requires pandas to be installed. Install with `pip install pandas`.

    Returns:
        A pandas dataframe.

    Raises:
        ImportError: If pandas is not installed.
    """
    try:
        return self.to_astropy().to_pandas()
    except ImportError:
        raise ImportError("pandas is required for this method. Install it with: pip install pandas")

CatalogsResponse

Bases: BaseModel

SED Builder API response to catalogs endpoint.

Contains information about all available catalogs in the SED Builder system, including their names, identifiers, error radii, and spectral classifications.

Attributes:

Name Type Description
response_info ResponseInfo

Status information about the API response.

catalogs list[Source]

List of catalog information entries.

Source code in sedbuilder/schemas.py
class CatalogsResponse(BaseModel):
    """SED Builder API response to `catalogs` endpoint.

    Contains information about all available catalogs in the SED Builder system,
    including their names, identifiers, error radii, and spectral classifications.

    Attributes:
        response_info: Status information about the API response.
        catalogs: List of catalog information entries.
    """

    response_info: ResponseInfo = Field(alias="ResponseInfo")
    catalogs: list[Source] = Field(alias="Catalogs")

    def is_successful(self) -> bool:
        """Check if the API response indicates success.

        Returns:
            True if the response status code is 'OK'.
        """
        return self.response_info.status_code == "OK"

    def to_list(self) -> list[dict]:
        """Converts catalog data to a list of dictionaries.

        Returns:
            A list of dictionaries, one per catalog, containing all catalog metadata.
        """
        return [c.model_dump() for c in self.catalogs]

is_successful()

Check if the API response indicates success.

Returns:

Type Description
bool

True if the response status code is 'OK'.

Source code in sedbuilder/schemas.py
def is_successful(self) -> bool:
    """Check if the API response indicates success.

    Returns:
        True if the response status code is 'OK'.
    """
    return self.response_info.status_code == "OK"

to_list()

Converts catalog data to a list of dictionaries.

Returns:

Type Description
list[dict]

A list of dictionaries, one per catalog, containing all catalog metadata.

Source code in sedbuilder/schemas.py
def to_list(self) -> list[dict]:
    """Converts catalog data to a list of dictionaries.

    Returns:
        A list of dictionaries, one per catalog, containing all catalog metadata.
    """
    return [c.model_dump() for c in self.catalogs]