Skip to main content
REST API теперь версия. Дополнительные сведения см. в разделе "О управлении версиями API".

Конечные точки REST API для отправки зависимостей

Используйте REST API для отправки зависимостей.

Сведения о отправке зависимостей

Rest API можно использовать для отправки зависимостей для проекта. Так вы сможете добавлять зависимости, например разрешаемые при компиляции или сборке программного обеспечения, в функцию графа зависимостей GitHub, чтобы создать более полную картину всех зависимостей проекта.

На графе зависимостей отображаются все зависимости, которые вы отправили через этот API, а также те, которые определены в файлах манифеста или блокировки, размещенных в репозитории (например, файл package-lock.json в проекте JavaScript). Дополнительные сведения о просмотре граф зависимостей см. в разделе Изучение зависимостей репозитория.

Отправленные зависимости будут получать Dependabot alerts и Dependabot security updates по всем известным уязвимостям. Вы получите только Dependabot alerts для зависимостей, которые находятся из одной из поддерживаемых экосистем для GitHub Advisory Database. Дополнительные сведения об этих экосистемах см. в разделе Сведения о базе данных GitHub Advisory. Для транзитивных зависимостей, отправленных через API отправки зависимостей, Dependabot автоматически открывает запросы на вытягивание для обновления родительской зависимости, если обновление доступно.

Отправленные зависимости будут отображаться в проверке зависимостей, но недоступны в аналитике зависимостей вашей организации.

Note

API проверки зависимостей и API отправки зависимостей работают вместе. Это означает, что API проверки зависимостей будет включать зависимости, отправленные через API отправки зависимостей.

Зависимости можно отправить в виде моментального снимка. Моментальный снимок — это набор зависимостей, связанных с SHA фиксации и другими метаданными, которые отражают текущее состояние репозитория для фиксации. Вы можете использовать предварительно созданные действия или создать собственные действия для отправки зависимостей в требуемом формате при каждом создании проекта. Дополнительные сведения см. в разделе Использование API отправки зависимостей.

Вы можете отправить несколько наборов зависимостей, которые будут включены в граф зависимостей. REST API использует job.correlator свойство и detector.name категорию моментального снимка, чтобы обеспечить последние отправки для каждого рабочего процесса. Само свойство correlator является основным полем, которое будет использоваться для различения независимых отправок. Например, в качестве correlator можно использовать простое сочетание двух переменных, доступных в выполнениях действий: <GITHUB_WORKFLOW> <GITHUB_JOB>.

Create a snapshot of dependencies for a repository

Create a new snapshot of a repository's dependencies.

The authenticated user must have access to the repository.

OAuth app tokens and personal access tokens (classic) need the repo scope to use this endpoint.

Подробные маркеры доступа для "Create a snapshot of dependencies for a repository

Эта конечная точка работает со следующими точными типами маркеров:

Маркер с точной детализацией должен иметь следующий набор разрешений.:

  • "Contents" repository permissions (write)

Параметры для "Create a snapshot of dependencies for a repository"

Заголовки
Имя., Тип, Description
accept string

Setting to application/vnd.github+json is recommended.

Параметры пути
Имя., Тип, Description
owner string Обязательное поле

The account owner of the repository. The name is not case sensitive.

repo string Обязательное поле

The name of the repository without the .git extension. The name is not case sensitive.

Параметры запроса
Имя., Тип, Description
version integer Обязательное поле

The version of the repository snapshot submission.

job object Обязательное поле
Имя., Тип, Description
id string Обязательное поле

The external ID of the job.

correlator string Обязательное поле

Correlator provides a key that is used to group snapshots submitted over time. Only the "latest" submitted snapshot for a given combination of job.correlator and detector.name will be considered when calculating a repository's current dependencies. Correlator should be as unique as it takes to distinguish all detection runs for a given "wave" of CI workflow you run. If you're using GitHub Actions, a good default value for this could be the environment variables GITHUB_WORKFLOW and GITHUB_JOB concatenated together. If you're using a build matrix, then you'll also need to add additional key(s) to distinguish between each submission inside a matrix variation.

html_url string

The url for the job.

sha string Обязательное поле

The commit SHA associated with this dependency snapshot. Maximum length: 40 characters.

ref string Обязательное поле

The repository branch that triggered this snapshot.

detector object Обязательное поле

A description of the detector used.

Имя., Тип, Description
name string Обязательное поле

The name of the detector used.

version string Обязательное поле

The version of the detector used.

url string Обязательное поле

The url of the detector used.

metadata object

User-defined metadata to store domain-specific information limited to 8 keys with scalar values.

manifests object

A collection of package manifests, which are a collection of related dependencies declared in a file or representing a logical group of dependencies.

Имя., Тип, Description
key object

A user-defined key to represent an item in manifests.

Имя., Тип, Description
name string Обязательное поле

The name of the manifest.

file object
Имя., Тип, Description
source_location string

The path of the manifest file relative to the root of the Git repository.

metadata object

User-defined metadata to store domain-specific information limited to 8 keys with scalar values.

resolved object

A collection of resolved package dependencies.

Имя., Тип, Description
key object

A user-defined key to represent an item in resolved.

Имя., Тип, Description
package_url string

Package-url (PURL) of dependency. See https://github.com/package-url/purl-spec for more details.

metadata object

User-defined metadata to store domain-specific information limited to 8 keys with scalar values.

relationship string

A notation of whether a dependency is requested directly by this manifest or is a dependency of another dependency.

Возможные значения: direct, indirect

scope string

A notation of whether the dependency is required for the primary build artifact (runtime) or is only used for development. Future versions of this specification may allow for more granular scopes.

Возможные значения: runtime, development

dependencies array of strings

Array of package-url (PURLs) of direct child dependencies.

scanned string Обязательное поле

The time at which the snapshot was scanned.

Коды состояния http-ответа для "Create a snapshot of dependencies for a repository"

Код состоянияОписание
201

Created

Примеры кода для "Create a snapshot of dependencies for a repository"

Если вы обращаетесь к GitHub в GHE.com, замените api.github.com выделенный поддомен api.SUBDOMAIN.ghe.comпредприятия.

Пример запроса

post/repos/{owner}/{repo}/dependency-graph/snapshots
curl -L \ -X POST \ -H "Accept: application/vnd.github+json" \ -H "Authorization: Bearer <YOUR-TOKEN>" \ -H "X-GitHub-Api-Version: 2022-11-28" \ https://api.github.com/repos/OWNER/REPO/dependency-graph/snapshots \ -d '{"version":0,"sha":"ce587453ced02b1526dfb4cb910479d431683101","ref":"refs/heads/main","job":{"correlator":"yourworkflowname_youractionname","id":"yourrunid"},"detector":{"name":"octo-detector","version":"0.0.1","url":"https://github.com/octo-org/octo-repo"},"scanned":"2022-06-14T20:25:00Z","manifests":{"package-lock.json":{"name":"package-lock.json","file":{"source_location":"src/package-lock.json"},"resolved":{"@actions/core":{"package_url":"pkg:/npm/%40actions/core@1.1.9","dependencies":["@actions/http-client"]},"@actions/http-client":{"package_url":"pkg:/npm/%40actions/http-client@1.0.7","dependencies":["tunnel"]},"tunnel":{"package_url":"pkg:/npm/tunnel@0.0.6"}}}}}'

Response

Status: 201
{ "id": 12345, "created_at": "2018-05-04T01:14:52Z", "message": "Dependency results for the repo have been successfully updated.", "result": "SUCCESS" }