如何通过REST API或脚本获取Nexus 3制品的时间戳、大小及名称并导出为JSON?
Hey there! Great question—Nexus 3's default Search and Asset APIs do skip some granular details like exact blob timestamps and sizes, but there are solid, straightforward ways to get this done using Groovy scripts (deployable as scheduled tasks), custom REST endpoints, or even shell tools if that's your preference. Let's break down each solution step by step:
1. Deployable Groovy Script Task (Recommended)
Nexus 3 comes with a built-in Groovy script engine that lets you tap directly into its internal storage APIs—this is the most efficient way to fetch all the details you need. You can run this script ad-hoc or deploy it as a scheduled task, and output results straight to a JSON file.
Here's a ready-to-use script that targets a specific repository, pulls artifact name, size, last modified timestamp, and saves the data as JSON:
import groovy.json.JsonBuilder import org.sonatype.nexus.repository.Repository import org.sonatype.nexus.repository.storage.Asset import org.sonatype.nexus.repository.storage.Query import org.sonatype.nexus.repository.storage.StorageFacet // Configure your target repository and output path here def targetRepo = "your-maven-repo" def outputFile = "/nexus-data/artifact-details.json" // Use a path accessible to Nexus // Fetch the repository instance Repository repo = repository.repositoryManager.get(targetRepo) StorageFacet storageLayer = repo.facet(StorageFacet) def storageTx = storageLayer.txSupplier().get() storageTx.begin() try { // Get all assets in the repository def assets = storageTx.findAssets(Query.builder().build(), [repo]) def artifactList = [] assets.each { Asset asset -> artifactList.add([ name: asset.name(), size: asset.size(), lastModified: asset.lastUpdated().toString(), repository: targetRepo, fullPath: asset.path() ]) } // Build and save JSON output def jsonOutput = new JsonBuilder(artifactList).toPrettyString() new File(outputFile).write(jsonOutput) log.info("Successfully saved ${artifactList.size()} artifact records to ${outputFile}") // Optional: Print to task logs instead of a file // println(jsonOutput) } finally { storageTx.close() }
How to use this:
- Head to Nexus UI → System → Scripts → Create script
- Set the type to
Groovy, paste the code, and updatetargetRepo/outputFileto match your setup - Run it immediately, or create a scheduled task (under System → Tasks) to execute it on a recurring basis
2. Custom REST API Endpoint
Yes, Nexus 3 supports adding custom REST endpoints via Groovy scripts. This lets you expose artifact details as a dedicated API that external tools can call on demand.
Here's a script to create a custom endpoint that returns artifact data for any repository:
import groovy.json.JsonBuilder import org.sonatype.nexus.repository.Repository import org.sonatype.nexus.repository.storage.Asset import org.sonatype.nexus.repository.storage.Query import org.sonatype.nexus.repository.storage.StorageFacet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse // Register endpoint: /service/rest/v1/custom/artifacts/{repository-name} route("/service/rest/v1/custom/artifacts/:repoName") { HttpServletRequest request, HttpServletResponse response -> def repoName = request.getAttribute("repoName") Repository targetRepo = repository.repositoryManager.get(repoName) if (!targetRepo) { response.status = 404 response.writer.write("Repository ${repoName} not found") return } StorageFacet storageLayer = targetRepo.facet(StorageFacet) def storageTx = storageLayer.txSupplier().get() storageTx.begin() try { def assets = storageTx.findAssets(Query.builder().build(), [targetRepo]) def artifactList = [] assets.each { Asset asset -> artifactList.add([ name: asset.name(), size: asset.size(), lastModified: asset.lastUpdated().toString(), repository: repoName, fullPath: asset.path() ]) } response.contentType = "application/json" response.writer.write(new JsonBuilder(artifactList).toPrettyString()) } finally { storageTx.close() } }
How to deploy:
- Create this as a Groovy script in Nexus (same steps as above)
- Run the script once—it will register the endpoint permanently (until Nexus restarts or you delete the script)
- Call it with curl:
curl -u admin:your-password http://your-nexus-url/service/rest/v1/custom/artifacts/your-repo-name
3. Shell Script Alternative (Using Default APIs + JQ)
If you prefer shell tools, you can combine Nexus' v1 Component API with the Blob Store API to piece together the missing details. Note this is slower for large repositories due to multiple API calls per asset.
Here's a sample bash script that saves results to artifacts.json:
#!/bin/bash NEXUS_URL="http://your-nexus-url" USER="admin" PASSWORD="your-nexus-password" TARGET_REPO="your-maven-repo" # Initialize JSON output file echo "[" > artifacts.json FIRST_ENTRY=true # Fetch all assets in the repository curl -s -u $USER:$PASSWORD "${NEXUS_URL}/service/rest/v1/components?repository=${TARGET_REPO}" | \ jq -r '.items[] | .assets[] | .downloadUrl' | while read -r ASSET_URL; do # Get asset metadata (includes blob ID) ASSET_META=$(curl -s -u $USER:$PASSWORD -H "Accept: application/json" "${ASSET_URL%/*}") BLOB_ID=$(echo "$ASSET_META" | jq -r '.blobId') # Fetch blob details (size + last modified) from blob store API BLOB_DETAILS=$(curl -s -u $USER:$PASSWORD "${NEXUS_URL}/service/rest/v1/blobstores/default/blobs/${BLOB_ID}") # Build artifact JSON entry ENTRY=$(jq -n \ --arg name "$(echo "$ASSET_META" | jq -r '.name')" \ --arg size "$(echo "$BLOB_DETAILS" | jq -r '.size')" \ --arg lastModified "$(echo "$BLOB_DETAILS" | jq -r '.lastUpdated')" \ '{name: $name, size: $size, lastModified: $lastModified}') # Append to JSON file (handle commas correctly) if [ "$FIRST_ENTRY" = true ]; then echo "$ENTRY" >> artifacts.json FIRST_ENTRY=false else echo ",$ENTRY" >> artifacts.json fi done echo "]" >> artifacts.json echo "Artifact details saved to artifacts.json"
This requires jq (a command-line JSON parser) to work.
Key Takeaways
- Groovy scripts are the most efficient option, as they directly access Nexus' internal storage without extra API overhead.
- Custom endpoints are perfect if you need to fetch this data dynamically from external systems.
- Shell scripts work but are better suited for small repositories or one-off tasks.
内容的提问来源于stack exchange,提问作者Samurai




