Retrieve attachments and attachment metadata

  • Release version: Yokohama
  • Updated January 30, 2025
  • 2 minutes to read
  • Summarize
    Summarized using AI
    This content was generated using new OpenAI-powered functionality. Results are provided on an as is basis and are not guaranteed to be accurate or complete.

    Summary of Retrieve attachments and attachment metadata

    The NowAttachmentService API in ServiceNow Yokohama release allows customers to manage attachments by performing CRUD operations and retrieving attachment metadata. This API supports guest users in the base ServiceNow system and enables uploading, downloading, deleting, validating attachments, and fetching their metadata.

    Show full answer Show less

    Using NowAttachmentService

    To use the API, instantiate the NowAttachmentService via the NowDataSDK by providing the ServiceNow instance URL. This service can then be injected into your application components for reuse.

    Fetching Attachment Metadata

    • Single Attachment Metadata: Retrieve metadata for a specific attachment by its sysid, returning a Response object with NowAttachmentMetadata.
    • Multiple Attachments Metadata: Use filter queries and limits to fetch metadata for multiple attachments, receiving a list of NowAttachmentMetadata objects.

    Handling Large Metadata Sets with Pagination

    For large volumes of metadata, the API provides a paginator method attachmentMetadataPaginator which returns a Paginator object. This object supports asynchronous iteration over metadata results with callback methods:

    • first(), last(), next(), previous() to navigate pages
    • hasNext(), hasPrevious(), isBusy() to check paginator state
    • observe() to register success and failure callbacks

    This enables efficient and controlled processing of large attachment metadata sets without overwhelming system resources.

    Practical Benefits for ServiceNow Customers

    • Seamlessly manage attachments linked to ServiceNow records, improving data handling and record completeness.
    • Validate attachment integrity by comparing computed hashes.
    • Efficiently query and paginate through attachment metadata to support integrations, audits, or reporting requirements.
    • Supports asynchronous, non-blocking operations for responsive application performance.

    The NowAttachmentService API enables you to perform CRUD operations on attachments and retrieve attachment metadata from your ServiceNow instance.

    Note:
    The NowAttachment API works for guest users in the base ServiceNow system.
    Using this API you can:
    • Upload attachments to your ServiceNow instance and associated them to a specific record.
    • Download one or more attachments.
    • Delete attachments.
    • Validate an attachment by comparing the computed hash of the attachment to the expected hash.
    • Download attachment metadata. This metadata is generated by your ServiceNow instance when an attachment is uploaded.

    For additional information on working with attachments, see Attachment API.

    The following shows how to instantiate the NowAttachmentService:
    /**
     * Helper class used to handle different Now service instances. 
     * It has an application scope or is a Singleton.
     */
    @Singleton
    class SdkManager @Inject constructor() {
    
    
        private var nowAttachmentService: NowAttachmentService? = null
    
        /**
         * Create the NowAttachmentService once in the lifetime of the application 
         * inside the Application class or another manager class
         * that will be injected into other classes via dagger/hilt.
         * NowAttachmentService should be created after initializing the NowSDK
         */
        suspend fun getNowAttachmentService(): NowAttachmentService? {
            if (nowAttachmentService != null) return nowAttachmentService
    
            return NowDataSDK.makeAttachmentService(URL("https://instance-name.service-now.com"))
                .getOrThrow()
                .also { this.nowAttachmentService = it }
        }
    }

    The following shows how to obtain a Call object that fetches metadata for a particular attachments. It creates an executable object that is able to perform the specified request and return Response<NowAttachmentMetadata>.

    suspend fun fetchMetadata(sysId: String) {
        val response = runCatching {
            sdkManager.getNowAttachmentService()?.attachmentMetadata(sysId)?.execute()
        }
    
        if (response.isSuccess) {
            val nowAttachmentMetadata = response.getOrNull()?.body
        } else {
            Log.e("NowSDK", "result not successful")
        }
    }

    The following shows how to obtain a Call object that fetches metadata for multiple attachments. It creates an executable object that is able to perform the specified request and return Response< List<NowAttachmentMetadata>>.

    suspend fun fetchMultipleMetadata() {
        val filterQuery = "content_type=text/plain"
        val limit = 5
    
        val response = runCatching {
            sdkManager.getNowAttachmentService()?.attachmentMetadata(Filter(filterQuery), limit)?.execute()
        }
    
        if (response.isSuccess) {
            val attachmentMetadataList = response.getOrNull()?.body
        } else {
            Log.e("NowSDK", "result not successful")
        }
    }

    Attachment metadata pagination

    You can use the NowAttachmentService methods to download attachment metadata for one or more attachments. When downloading metadata from multiple attachments, you may want to use the NowAttachmentService - attachmentMetadataPaginator(filter: Filter? = null, limit: Int? = null) method, which returns a Paginator object that enables you to easily iterate over the potentially large amount of data that is returned.

    You can then iterate through the returned metadata using Paginator methods and receiving the response in the observe() callback.
     suspend fun createAttachmentMetadataPaginator() {
      val filterQuery: String = "content_type=text/plain"
      val filter = filterQuery.let(::Filter)
      val limit = 10
    
      val paginator = sdkmanager.getNowAttachmentService()?.attachmentMetadataPaginator(filter, limit)
        ?.observe(object : PaginatorCallBack<NowAttachmentMetadata> {
          override fun onSuccess(response: Response<List<NowAttachmentMetadata>>) {
            // Handle response
          }
    
          override fun onFailure(e: NowDataError) {
            // Handle error
          }
    
        })
        ?: throw Exception("Response is null")
    
      // Use paginator operators to navigate. Example
      while (paginator.hasNext() && !paginator.isBusy()) {
        paginator.next()
      }
    }
    The returned Paginator object provides the following methods that enable you to page through the returned records. You must first call the observe() function to set the Paginator's callback.
    • first()
    • hasNext()
    • hasPrevious
    • isBusy
    • last()
    • next()
    • observe()
    • previous()
    • reset()
    Note:
    Some Paginator methods may throw an exception, such as when there are no more pages to fetch.