Retrieve attachments and attachment metadata

  • Release version: Washingtondc
  • Updated February 1, 2024
  • 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 allows ServiceNow customers to perform CRUD operations on attachments and access metadata associated with those attachments. This API is available for guest users in the base ServiceNow system, enabling functionalities like uploading, downloading, deleting attachments, and validating them through hash comparison.

    Show full answer Show less

    Key Features

    • Upload Attachments: Attach files to specific records in your ServiceNow instance.
    • Download Attachments: Retrieve one or multiple attachments as needed.
    • Delete Attachments: Remove attachments from your instance.
    • Validate Attachments: Ensure the integrity of attachments by comparing computed and expected hashes.
    • Retrieve Metadata: Access metadata generated during attachment uploads, useful for tracking and management.
    • Pagination: Efficiently handle large sets of attachment metadata using the Paginator object.

    Key Outcomes

    By utilizing the NowAttachmentService, customers can streamline attachment management within their ServiceNow instances, ensuring effective handling of documents related to service requests or other records. The ability to paginate through large amounts of metadata also enhances performance and usability, allowing customers to manage attachments effectively without overwhelming their systems.

    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.