Skip to content

Containerlab Orchestrator API Package

containerlab_orchestrator.api

REST API for the containerlab_orchestrator app.

serializers

REST API serializers for the containerlab_orchestrator app.

ContainerlabHostSerializer

Bases: TaggedModelSerializerMixin, NautobotModelSerializer

Serializer for ContainerlabHost.

The Secrets Group shows as a reference, never as a secret value.

Source code in containerlab_orchestrator/api/serializers.py
class ContainerlabHostSerializer(TaggedModelSerializerMixin, NautobotModelSerializer):  # pylint: disable=too-many-ancestors
    """Serializer for ContainerlabHost.

    The Secrets Group shows as a reference, never as a secret value.
    """

    class Meta:
        """Meta attributes for ContainerlabHostSerializer."""

        model = ContainerlabHost
        fields = "__all__"
Meta

Meta attributes for ContainerlabHostSerializer.

Source code in containerlab_orchestrator/api/serializers.py
class Meta:
    """Meta attributes for ContainerlabHostSerializer."""

    model = ContainerlabHost
    fields = "__all__"

InterfaceMappingSerializer

Bases: ValidatedModelSerializer

Serializer for InterfaceMapping.

The model full_clean() checks the unique names, so a duplicate has the same error key __all__ as the model.

Source code in containerlab_orchestrator/api/serializers.py
class InterfaceMappingSerializer(ValidatedModelSerializer):  # pylint: disable=too-many-ancestors
    """Serializer for InterfaceMapping.

    The model full_clean() checks the unique names, so a duplicate has the same error key `__all__` as the model.
    """

    class Meta:
        """Meta attributes for InterfaceMappingSerializer."""

        model = InterfaceMapping
        fields = "__all__"
        validators = []
Meta

Meta attributes for InterfaceMappingSerializer.

Source code in containerlab_orchestrator/api/serializers.py
class Meta:
    """Meta attributes for InterfaceMappingSerializer."""

    model = InterfaceMapping
    fields = "__all__"
    validators = []

LabNodeSerializer

Bases: BaseModelSerializer

Read-only serializer for LabNode.

Source code in containerlab_orchestrator/api/serializers.py
class LabNodeSerializer(BaseModelSerializer):
    """Read-only serializer for LabNode."""

    class Meta:
        """Meta attributes for LabNodeSerializer."""

        model = LabNode
        fields = "__all__"
Meta

Meta attributes for LabNodeSerializer.

Source code in containerlab_orchestrator/api/serializers.py
class Meta:
    """Meta attributes for LabNodeSerializer."""

    model = LabNode
    fields = "__all__"

LabOwnerSerializer

Bases: BaseModelSerializer

Read-only serializer that shows a lab owner with the username and no other user data.

Source code in containerlab_orchestrator/api/serializers.py
class LabOwnerSerializer(BaseModelSerializer):
    """Read-only serializer that shows a lab owner with the username and no other user data."""

    class Meta:
        """Meta attributes for LabOwnerSerializer."""

        model = get_user_model()
        fields = ["id", "object_type", "url", "display", "username"]
        is_nested = True
Meta

Meta attributes for LabOwnerSerializer.

Source code in containerlab_orchestrator/api/serializers.py
class Meta:
    """Meta attributes for LabOwnerSerializer."""

    model = get_user_model()
    fields = ["id", "object_type", "url", "display", "username"]
    is_nested = True

LabSerializer

Bases: TaggedModelSerializerMixin, NautobotModelSerializer

Serializer for Lab.

The model clean() checks the unique name, so a duplicate gets the name error key. The topology YAML is not a field, because it can be large; the topology action of the lab downloads it.

Source code in containerlab_orchestrator/api/serializers.py
class LabSerializer(TaggedModelSerializerMixin, NautobotModelSerializer):  # pylint: disable=too-many-ancestors
    """Serializer for Lab.

    The model `clean()` checks the unique name, so a duplicate gets the `name` error key. The topology YAML is
    not a field, because it can be large; the topology action of the lab downloads it.
    """

    class Meta:
        """Meta attributes for LabSerializer."""

        model = Lab
        exclude = ["topology_yaml"]
        validators = []

    def validate(self, attrs):
        """On create, make the request user the owner and set the Planned status.

        Raises:
            ValidationError: If the request is not a REST API request of a signed-in user, as in the CSV import job.
        """
        if self.instance is None:
            request = self.context.get("request")
            if not isinstance(request, Request) or not request.user.is_authenticated:
                raise serializers.ValidationError("Use the add form or the REST API to add a lab.")
            lab = Lab()
            lab.set_create_defaults(request.user)
            attrs["owner"] = lab.owner
            attrs["status"] = lab.status
        return super().validate(attrs)

    def build_nested_field(self, field_name, relation_info, nested_depth):
        """Show the owner with `LabOwnerSerializer` at each depth from 1, with no other user data."""
        if field_name == "owner":
            return LabOwnerSerializer, get_nested_relation_kwargs(relation_info)
        return super().build_nested_field(field_name, relation_info, nested_depth)
Meta

Meta attributes for LabSerializer.

Source code in containerlab_orchestrator/api/serializers.py
class Meta:
    """Meta attributes for LabSerializer."""

    model = Lab
    exclude = ["topology_yaml"]
    validators = []
build_nested_field(field_name, relation_info, nested_depth)

Show the owner with LabOwnerSerializer at each depth from 1, with no other user data.

Source code in containerlab_orchestrator/api/serializers.py
def build_nested_field(self, field_name, relation_info, nested_depth):
    """Show the owner with `LabOwnerSerializer` at each depth from 1, with no other user data."""
    if field_name == "owner":
        return LabOwnerSerializer, get_nested_relation_kwargs(relation_info)
    return super().build_nested_field(field_name, relation_info, nested_depth)
validate(attrs)

On create, make the request user the owner and set the Planned status.

Raises:

Type Description
ValidationError

If the request is not a REST API request of a signed-in user, as in the CSV import job.

Source code in containerlab_orchestrator/api/serializers.py
def validate(self, attrs):
    """On create, make the request user the owner and set the Planned status.

    Raises:
        ValidationError: If the request is not a REST API request of a signed-in user, as in the CSV import job.
    """
    if self.instance is None:
        request = self.context.get("request")
        if not isinstance(request, Request) or not request.user.is_authenticated:
            raise serializers.ValidationError("Use the add form or the REST API to add a lab.")
        lab = Lab()
        lab.set_create_defaults(request.user)
        attrs["owner"] = lab.owner
        attrs["status"] = lab.status
    return super().validate(attrs)

NodeMappingSerializer

Bases: TaggedModelSerializerMixin, NautobotModelSerializer

Serializer for NodeMapping.

Source code in containerlab_orchestrator/api/serializers.py
class NodeMappingSerializer(TaggedModelSerializerMixin, NautobotModelSerializer):  # pylint: disable=too-many-ancestors
    """Serializer for NodeMapping."""

    class Meta:
        """Meta attributes for NodeMappingSerializer."""

        model = NodeMapping
        fields = "__all__"
Meta

Meta attributes for NodeMappingSerializer.

Source code in containerlab_orchestrator/api/serializers.py
class Meta:
    """Meta attributes for NodeMappingSerializer."""

    model = NodeMapping
    fields = "__all__"

urls

REST API URL patterns for the containerlab_orchestrator app.

views

REST API views for the containerlab_orchestrator app.

TOPOLOGY_RENDERERS = [renderer for renderer in api_settings.DEFAULT_RENDERER_CLASSES if renderer.format != 'csv'] module-attribute

The renderers of the topology download. With no CSV renderer, a CSV request cannot rename the file.

ContainerlabHostViewSet

Bases: NautobotModelViewSet

REST API viewset for ContainerlabHost.

Source code in containerlab_orchestrator/api/views.py
class ContainerlabHostViewSet(NautobotModelViewSet):  # pylint: disable=too-many-ancestors
    """REST API viewset for ContainerlabHost."""

    queryset = ContainerlabHost.objects.all()
    serializer_class = ContainerlabHostSerializer
    filterset_class = ContainerlabHostFilterSet

InterfaceMappingViewSet

Bases: ModelViewSet

REST API viewset for InterfaceMapping.

Source code in containerlab_orchestrator/api/views.py
class InterfaceMappingViewSet(ModelViewSet):  # pylint: disable=too-many-ancestors
    """REST API viewset for InterfaceMapping."""

    queryset = InterfaceMapping.objects.select_related(
        "node_mapping__device_type__manufacturer", "node_mapping__platform"
    )
    serializer_class = InterfaceMappingSerializer
    filterset_class = InterfaceMappingFilterSet

LabNodeViewSet

Bases: ReadOnlyModelViewSet

Read-only REST API viewset for LabNode. The Build and Inspect jobs write the rows.

Source code in containerlab_orchestrator/api/views.py
class LabNodeViewSet(ReadOnlyModelViewSet):  # pylint: disable=too-many-ancestors
    """Read-only REST API viewset for LabNode. The Build and Inspect jobs write the rows."""

    queryset = LabNode.objects.select_related("lab__host", "device")
    serializer_class = LabNodeSerializer
    filterset_class = LabNodeFilterSet

LabViewSet

Bases: NautobotModelViewSet

REST API viewset for Lab.

Source code in containerlab_orchestrator/api/views.py
class LabViewSet(NautobotModelViewSet):  # pylint: disable=too-many-ancestors
    """REST API viewset for Lab."""

    queryset = Lab.objects.select_related("host", "owner", "status", "dynamic_group")
    serializer_class = LabSerializer
    filterset_class = LabFilterSet

    @extend_schema(
        methods=["get"],
        description="Download the stored topology YAML of the lab as `<lab>.clab.yml`.",
        responses={(200, "application/yaml"): OpenApiTypes.STR},
    )
    @action(detail=True, methods=["get"], url_path="topology", renderer_classes=TOPOLOGY_RENDERERS)
    def topology(self, request, pk=None):  # pylint: disable=unused-argument
        """Download the stored topology YAML of the lab as `<lab>.clab.yml`.

        Raises:
            NotFound: If the lab has no topology YAML.
        """
        lab = self.get_object()
        if not lab.topology_yaml:
            raise NotFound(NO_TOPOLOGY_MESSAGE.format(lab=lab))
        return HttpResponse(
            lab.topology_yaml,
            content_type="application/yaml",
            headers={"Content-Disposition": content_disposition_header(True, f"{lab.name}.clab.yml")},
        )
topology(request, pk=None)

Download the stored topology YAML of the lab as <lab>.clab.yml.

Raises:

Type Description
NotFound

If the lab has no topology YAML.

Source code in containerlab_orchestrator/api/views.py
@extend_schema(
    methods=["get"],
    description="Download the stored topology YAML of the lab as `<lab>.clab.yml`.",
    responses={(200, "application/yaml"): OpenApiTypes.STR},
)
@action(detail=True, methods=["get"], url_path="topology", renderer_classes=TOPOLOGY_RENDERERS)
def topology(self, request, pk=None):  # pylint: disable=unused-argument
    """Download the stored topology YAML of the lab as `<lab>.clab.yml`.

    Raises:
        NotFound: If the lab has no topology YAML.
    """
    lab = self.get_object()
    if not lab.topology_yaml:
        raise NotFound(NO_TOPOLOGY_MESSAGE.format(lab=lab))
    return HttpResponse(
        lab.topology_yaml,
        content_type="application/yaml",
        headers={"Content-Disposition": content_disposition_header(True, f"{lab.name}.clab.yml")},
    )

NodeMappingViewSet

Bases: NautobotModelViewSet

REST API viewset for NodeMapping.

Source code in containerlab_orchestrator/api/views.py
class NodeMappingViewSet(NautobotModelViewSet):  # pylint: disable=too-many-ancestors
    """REST API viewset for NodeMapping."""

    queryset = NodeMapping.objects.select_related("device_type__manufacturer", "platform")
    serializer_class = NodeMappingSerializer
    filterset_class = NodeMappingFilterSet