class NavigationService
NavigationService is a REST-based service class for managing SharePoint navigation operations, including global navigation, menu states, and publishing navigation providers.
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/navigation/navigation_service.py
12 - 140
moderate
Purpose
This class serves as the entry point for interacting with SharePoint's navigation REST API. It provides methods to retrieve and manage navigation menus, check navigation provider types, enable/disable global navigation, and work with menu states and nodes. It inherits from Entity and uses the SharePoint REST API to perform operations on site navigation structures.
Source Code
class NavigationService(Entity):
"""The entry point for REST-based navigation service operations."""
def __init__(self, context):
"""The entry point for REST-based navigation service operations."""
static_path = ResourcePath(
"Microsoft.SharePoint.Navigation.REST.NavigationServiceRest"
)
super(NavigationService, self).__init__(context, static_path)
def get_publishing_navigation_provider_type(
self, map_provider_name=NavigationProviderType.SPNavigationProvider
):
"""
Gets a publishing navigation provider type when publishing feature is turned on for the site (2).
If navigation provider is not found on the site MUST return InvalidSiteMapProvider type.
:param str map_provider_name: The server will use "SPNavigationProvider" as provider name
if mapProviderName is not specified.
"""
return_type = ClientResult(self.context)
params = {"mapProviderName": map_provider_name}
qry = ServiceOperationQuery(
self, "GetPublishingNavigationProviderType", params, None, None, return_type
)
self.context.add_query(qry)
return return_type
def global_nav(self):
""""""
return_type = ClientResult(self.context, MenuState())
qry = ServiceOperationQuery(self, "GlobalNav", None, None, None, return_type)
self.context.add_query(qry)
return return_type
def global_nav_enabled(self):
""" """
return_type = ClientResult(self.context, bool())
qry = ServiceOperationQuery(
self, "GlobalNavEnabled", None, None, None, return_type
)
self.context.add_query(qry)
return return_type
def set_global_nav_enabled(self, is_enabled):
"""
:param bool is_enabled:
"""
qry = ServiceOperationQuery(
self, "SetGlobalNavEnabled", None, {"isEnabled": is_enabled}
)
self.context.add_query(qry)
return self
def menu_node_key(self, current_url, map_provider_name=None):
"""
Returns the unique key for a node within the menu tree. If a key cannot be found, an exception is returned.
:param str current_url: A URL relative to the site collection identifying the node within the menu tree.
:param str map_provider_name: The name identifying a provider to use for the lookup
"""
return_type = ClientResult(self.context, str())
params = {"currentUrl": current_url, "mapProviderName": map_provider_name}
qry = ServiceOperationQuery(
self, "MenuNodeKey", None, params, None, return_type
)
self.context.add_query(qry)
return return_type
def menu_state(
self, menu_node_key, map_provider_name, depth=None, custom_properties=None
):
"""
Returns the menu tree rooted at the specified root node for a given provider.
:param str menu_node_key: A unique key identifying the node that will be used as root node in the returned
result
:param str map_provider_name: The name identifying a provider to use for the lookup
:param int depth: The number of levels to include in the returned site map. If no value is specified,
a depth of 10 is used.
:param str custom_properties: A comma separated list of custom properties to request.
The character "\" is used to escape commas, allowing comma to be part of the property names.
"""
return_type = ClientResult(self.context, MenuState())
payload = {
"menuNodeKey": menu_node_key,
"mapProviderName": map_provider_name,
"depth": depth,
"customProperties": custom_properties,
}
qry = ServiceOperationQuery(self, "MenuState", None, payload, None, return_type)
self.context.add_query(qry)
return return_type
def save_menu_state(self, menu_node_key, map_provider_name):
"""Updates the menu tree rooted at the specified root node for a given provider.
:param str menu_node_key: A unique key identifying the node that will be used as root node in the returned
result
:param str map_provider_name: The name identifying a provider to use for the lookup
"""
return_type = ClientResult(self.context)
payload = {"menuNodeKey": menu_node_key, "mapProviderName": map_provider_name}
qry = ServiceOperationQuery(
self, "SaveMenuState", None, payload, None, return_type
)
self.context.add_query(qry)
return return_type
@property
def home_site_settings(self):
return self.properties.get(
"HomeSiteSettings",
HomeSiteNavigationSettings(
self.context, ResourcePath("HomeSiteSettings", self.resource_path)
),
)
def get_property(self, name, default_value=None):
if default_value is None:
property_mapping = {
"HomeSiteSettings": self.home_site_settings,
}
default_value = property_mapping.get(name, None)
return super(NavigationService, self).get_property(name, default_value)
@property
def entity_type_name(self):
return "Microsoft.SharePoint.Navigation.REST.NavigationServiceRest"
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
Entity | - |
Parameter Details
context: A SharePoint client context object that provides the connection and authentication information needed to communicate with the SharePoint REST API. This context is used to execute queries and manage the service's lifecycle.
Return Value
Instantiation returns a NavigationService object configured with the provided context and a static resource path pointing to 'Microsoft.SharePoint.Navigation.REST.NavigationServiceRest'. Methods return either ClientResult objects (which wrap the actual return values and are resolved after query execution) or self (for fluent chaining). Specific return types include: MenuState objects for navigation menus, boolean values for enabled states, string values for keys, and NavigationProviderType enums.
Class Interface
Methods
__init__(self, context)
Purpose: Initializes the NavigationService with a SharePoint client context and sets up the static resource path
Parameters:
context: SharePoint client context object for API communication
Returns: None (constructor)
get_publishing_navigation_provider_type(self, map_provider_name=NavigationProviderType.SPNavigationProvider) -> ClientResult
Purpose: Gets the publishing navigation provider type when the publishing feature is enabled for the site
Parameters:
map_provider_name: The provider name to query (defaults to 'SPNavigationProvider'). Returns InvalidSiteMapProvider if not found
Returns: ClientResult wrapping the NavigationProviderType enum value
global_nav(self) -> ClientResult
Purpose: Retrieves the global navigation menu state for the site
Returns: ClientResult wrapping a MenuState object containing the global navigation structure
global_nav_enabled(self) -> ClientResult
Purpose: Checks whether global navigation is enabled for the site
Returns: ClientResult wrapping a boolean indicating if global navigation is enabled
set_global_nav_enabled(self, is_enabled: bool) -> NavigationService
Purpose: Enables or disables global navigation for the site
Parameters:
is_enabled: Boolean value to enable (True) or disable (False) global navigation
Returns: Self (NavigationService instance) for method chaining
menu_node_key(self, current_url: str, map_provider_name: str = None) -> ClientResult
Purpose: Returns the unique key for a node within the menu tree based on a URL
Parameters:
current_url: A URL relative to the site collection identifying the node within the menu treemap_provider_name: Optional name identifying a provider to use for the lookup
Returns: ClientResult wrapping a string containing the unique menu node key. Raises exception if key cannot be found
menu_state(self, menu_node_key: str, map_provider_name: str, depth: int = None, custom_properties: str = None) -> ClientResult
Purpose: Returns the menu tree rooted at the specified node for a given provider
Parameters:
menu_node_key: A unique key identifying the node that will be used as root node in the returned resultmap_provider_name: The name identifying a provider to use for the lookupdepth: The number of levels to include in the returned site map (defaults to 10 if not specified)custom_properties: A comma separated list of custom properties to request. Use backslash to escape commas in property names
Returns: ClientResult wrapping a MenuState object containing the navigation tree structure
save_menu_state(self, menu_node_key: str, map_provider_name: str) -> ClientResult
Purpose: Updates the menu tree rooted at the specified root node for a given provider
Parameters:
menu_node_key: A unique key identifying the node that will be used as root nodemap_provider_name: The name identifying a provider to use for the update
Returns: ClientResult object (empty result indicating success or failure of the operation)
home_site_settings(self) -> HomeSiteNavigationSettings
property
Purpose: Property that retrieves the home site navigation settings
Returns: HomeSiteNavigationSettings object containing home site navigation configuration
get_property(self, name: str, default_value=None)
Purpose: Retrieves a property value by name with optional default value, overriding Entity's get_property method
Parameters:
name: The name of the property to retrievedefault_value: Optional default value to return if property is not found
Returns: The property value or default_value if not found. Maps 'HomeSiteSettings' to home_site_settings property
entity_type_name(self) -> str
property
Purpose: Property that returns the SharePoint entity type name for this service
Returns: String 'Microsoft.SharePoint.Navigation.REST.NavigationServiceRest'
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
context |
ClientContext | The SharePoint client context used for executing REST API queries (inherited from Entity) | instance |
resource_path |
ResourcePath | The resource path pointing to 'Microsoft.SharePoint.Navigation.REST.NavigationServiceRest' (inherited from Entity) | instance |
properties |
dict | Dictionary storing cached properties like HomeSiteSettings (inherited from Entity) | instance |
Dependencies
office365
Required Imports
from office365.runtime.client_result import ClientResult
from office365.runtime.paths.resource_path import ResourcePath
from office365.runtime.queries.service_operation import ServiceOperationQuery
from office365.sharepoint.entity import Entity
from office365.sharepoint.navigation.home_site_navigation_settings import HomeSiteNavigationSettings
from office365.sharepoint.navigation.menu_state import MenuState
from office365.sharepoint.navigation.provider_type import NavigationProviderType
Usage Example
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.navigation.navigation_service import NavigationService
from office365.sharepoint.navigation.provider_type import NavigationProviderType
# Create SharePoint context
ctx = ClientContext('https://yourtenant.sharepoint.com/sites/yoursite').with_credentials(user_credentials)
# Instantiate NavigationService
nav_service = NavigationService(ctx)
# Check if global navigation is enabled
result = nav_service.global_nav_enabled()
ctx.execute_query()
print(f"Global nav enabled: {result.value}")
# Get global navigation menu
menu_result = nav_service.global_nav()
ctx.execute_query()
print(f"Menu nodes: {menu_result.value}")
# Enable global navigation
nav_service.set_global_nav_enabled(True)
ctx.execute_query()
# Get menu node key for a URL
key_result = nav_service.menu_node_key('/sites/yoursite/pages/home.aspx')
ctx.execute_query()
print(f"Node key: {key_result.value}")
# Get menu state with specific depth
menu_state = nav_service.menu_state(
menu_node_key='1002',
map_provider_name='SPNavigationProvider',
depth=3
)
ctx.execute_query()
print(f"Menu state: {menu_state.value}")
Best Practices
- Always call ctx.execute_query() after invoking service methods to execute the queued operations and retrieve results
- Use ClientResult.value property to access the actual return value after query execution
- Chain multiple operations before calling execute_query() to batch requests and improve performance
- Ensure the SharePoint context has appropriate permissions before attempting navigation modifications
- For set_global_nav_enabled(), the method returns self to allow method chaining
- When using menu_state(), specify an appropriate depth to avoid retrieving excessive data
- The map_provider_name parameter defaults to 'SPNavigationProvider' if not specified in get_publishing_navigation_provider_type()
- Handle exceptions that may occur if navigation providers are not found or if the publishing feature is not enabled
- Use menu_node_key() to retrieve valid keys before calling menu_state() or save_menu_state()
- The home_site_settings property is lazily loaded and cached in the properties dictionary
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class HomeSiteNavigationSettings 77.4% similar
-
class Navigation 76.3% similar
-
class NavigationNodeCollection 68.1% similar
-
class SuiteNavData 65.9% similar
-
class SitePageService 65.1% similar