This commit is contained in:
docubot 2022-12-09 09:04:43 -08:00 коммит произвёл GitHub
Родитель 2e564703f4
Коммит 3a7da0d517
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
11 изменённых файлов: 265 добавлений и 606 удалений

Просмотреть файл

@ -191,6 +191,7 @@ translations/pt-BR/content/organizations/restricting-access-to-your-organization
translations/pt-BR/content/pages/getting-started-with-github-pages/adding-a-theme-to-your-github-pages-site-with-the-theme-chooser.md,file deleted because it no longer exists in main
translations/pt-BR/content/pull-requests/collaborating-with-pull-requests/working-with-forks/configuring-a-remote-for-a-fork.md,file deleted because it no longer exists in main
translations/pt-BR/content/pull-requests/collaborating-with-pull-requests/working-with-forks/merging-an-upstream-repository-into-your-fork.md,file deleted because it no longer exists in main
translations/pt-BR/content/rest/guides/traversing-with-pagination.md,file deleted because it no longer exists in main
translations/pt-BR/content/rest/reference/actions.md,file deleted because it no longer exists in main
translations/pt-BR/content/rest/reference/activity.md,file deleted because it no longer exists in main
translations/pt-BR/content/rest/reference/apps.md,file deleted because it no longer exists in main
@ -556,6 +557,7 @@ translations/pt-BR/content/admin/enterprise-management/caching-repositories/conf
translations/pt-BR/content/admin/enterprise-management/caching-repositories/index.md,rendering error
translations/pt-BR/content/admin/enterprise-management/configuring-clustering/cluster-network-configuration.md,broken liquid tags
translations/pt-BR/content/admin/enterprise-management/configuring-clustering/configuring-high-availability-replication-for-a-cluster.md,broken liquid tags
translations/pt-BR/content/admin/enterprise-management/configuring-high-availability/initiating-a-failover-to-your-replica-appliance.md,broken liquid tags
translations/pt-BR/content/admin/enterprise-management/monitoring-your-appliance/accessing-the-monitor-dashboard.md,broken liquid tags
translations/pt-BR/content/admin/enterprise-management/monitoring-your-appliance/configuring-collectd.md,broken liquid tags
translations/pt-BR/content/admin/enterprise-management/monitoring-your-appliance/generating-a-health-check-for-your-enterprise.md,broken liquid tags
@ -943,12 +945,12 @@ translations/pt-BR/content/rest/enterprise-admin/pre-receive-hooks.md,broken liq
translations/pt-BR/content/rest/enterprise-admin/repo-pre-receive-hooks.md,broken liquid tags
translations/pt-BR/content/rest/enterprise-admin/scim.md,rendering error
translations/pt-BR/content/rest/enterprise-admin/users.md,broken liquid tags
translations/pt-BR/content/rest/guides/traversing-with-pagination.md,rendering error
translations/pt-BR/content/rest/guides/working-with-comments.md,broken liquid tags
translations/pt-BR/content/rest/migrations/source-imports.md,broken liquid tags
translations/pt-BR/content/rest/overview/api-previews.md,rendering error
translations/pt-BR/content/rest/overview/other-authentication-methods.md,rendering error
translations/pt-BR/content/rest/overview/permissions-required-for-github-apps.md,rendering error
translations/pt-BR/content/rest/overview/resources-in-the-rest-api.md,broken liquid tags
translations/pt-BR/content/rest/packages.md,broken liquid tags
translations/pt-BR/content/rest/projects/projects.md,broken liquid tags
translations/pt-BR/content/rest/scim.md,broken liquid tags
@ -1154,7 +1156,6 @@ translations/pt-BR/data/reusables/repositories/sidebar-notifications.md,renderin
translations/pt-BR/data/reusables/repositories/suggest-changes.md,broken liquid tags
translations/pt-BR/data/reusables/repositories/tracks-vulnerabilities.md,broken liquid tags
translations/pt-BR/data/reusables/repositories/you-can-fork.md,broken liquid tags
translations/pt-BR/data/reusables/rest-api/dotcom-only-guide-note.md,rendering error
translations/pt-BR/data/reusables/saml/about-authorized-credentials.md,broken liquid tags
translations/pt-BR/data/reusables/saml/about-linked-identities.md,broken liquid tags
translations/pt-BR/data/reusables/saml/about-saml-access-enterprise-account.md,broken liquid tags

1 file reason
191 translations/pt-BR/content/pages/getting-started-with-github-pages/adding-a-theme-to-your-github-pages-site-with-the-theme-chooser.md file deleted because it no longer exists in main
192 translations/pt-BR/content/pull-requests/collaborating-with-pull-requests/working-with-forks/configuring-a-remote-for-a-fork.md file deleted because it no longer exists in main
193 translations/pt-BR/content/pull-requests/collaborating-with-pull-requests/working-with-forks/merging-an-upstream-repository-into-your-fork.md file deleted because it no longer exists in main
194 translations/pt-BR/content/rest/guides/traversing-with-pagination.md file deleted because it no longer exists in main
195 translations/pt-BR/content/rest/reference/actions.md file deleted because it no longer exists in main
196 translations/pt-BR/content/rest/reference/activity.md file deleted because it no longer exists in main
197 translations/pt-BR/content/rest/reference/apps.md file deleted because it no longer exists in main
557 translations/pt-BR/content/admin/enterprise-management/caching-repositories/index.md rendering error
558 translations/pt-BR/content/admin/enterprise-management/configuring-clustering/cluster-network-configuration.md broken liquid tags
559 translations/pt-BR/content/admin/enterprise-management/configuring-clustering/configuring-high-availability-replication-for-a-cluster.md broken liquid tags
560 translations/pt-BR/content/admin/enterprise-management/configuring-high-availability/initiating-a-failover-to-your-replica-appliance.md broken liquid tags
561 translations/pt-BR/content/admin/enterprise-management/monitoring-your-appliance/accessing-the-monitor-dashboard.md broken liquid tags
562 translations/pt-BR/content/admin/enterprise-management/monitoring-your-appliance/configuring-collectd.md broken liquid tags
563 translations/pt-BR/content/admin/enterprise-management/monitoring-your-appliance/generating-a-health-check-for-your-enterprise.md broken liquid tags
945 translations/pt-BR/content/rest/enterprise-admin/repo-pre-receive-hooks.md broken liquid tags
946 translations/pt-BR/content/rest/enterprise-admin/scim.md rendering error
947 translations/pt-BR/content/rest/enterprise-admin/users.md broken liquid tags
translations/pt-BR/content/rest/guides/traversing-with-pagination.md rendering error
948 translations/pt-BR/content/rest/guides/working-with-comments.md broken liquid tags
949 translations/pt-BR/content/rest/migrations/source-imports.md broken liquid tags
950 translations/pt-BR/content/rest/overview/api-previews.md rendering error
951 translations/pt-BR/content/rest/overview/other-authentication-methods.md rendering error
952 translations/pt-BR/content/rest/overview/permissions-required-for-github-apps.md rendering error
953 translations/pt-BR/content/rest/overview/resources-in-the-rest-api.md broken liquid tags
954 translations/pt-BR/content/rest/packages.md broken liquid tags
955 translations/pt-BR/content/rest/projects/projects.md broken liquid tags
956 translations/pt-BR/content/rest/scim.md broken liquid tags
1156 translations/pt-BR/data/reusables/repositories/suggest-changes.md broken liquid tags
1157 translations/pt-BR/data/reusables/repositories/tracks-vulnerabilities.md broken liquid tags
1158 translations/pt-BR/data/reusables/repositories/you-can-fork.md broken liquid tags
translations/pt-BR/data/reusables/rest-api/dotcom-only-guide-note.md rendering error
1159 translations/pt-BR/data/reusables/saml/about-authorized-credentials.md broken liquid tags
1160 translations/pt-BR/data/reusables/saml/about-linked-identities.md broken liquid tags
1161 translations/pt-BR/data/reusables/saml/about-saml-access-enterprise-account.md broken liquid tags

Просмотреть файл

@ -1,6 +1,6 @@
---
title: Iniciar failover do appliance réplica
intro: 'É possível fazer failover de um appliance réplica do {% data variables.product.prodname_ghe_server %} usando a linha de comando para manutenção e teste ou em caso de falha do appliance primário.'
title: Initiating a failover to your replica appliance
intro: 'You can failover to a {% data variables.product.prodname_ghe_server %} replica appliance using the command line for maintenance and testing, or if the primary appliance fails.'
redirect_from:
- /enterprise/admin/installation/initiating-a-failover-to-your-replica-appliance
- /enterprise/admin/enterprise-management/initiating-a-failover-to-your-replica-appliance
@ -13,59 +13,60 @@ topics:
- High availability
- Infrastructure
shortTitle: Initiate failover to appliance
ms.openlocfilehash: 65e522d2a7b466c4f75cea087760ecb3001317a7
ms.sourcegitcommit: 3ea3ccb5af64bd7d9e4699757db38fdd8f98cde7
ms.translationtype: HT
ms.contentlocale: pt-BR
ms.lasthandoff: 07/12/2022
ms.locfileid: '147076696'
---
O tempo do failover dependerá do tempo necessário para promover manualmente a réplica e redirecionar o tráfego. Em média, o procedimento leva de dois a dez minutos.
The time required to failover depends on how long it takes to manually promote the replica and redirect traffic. The average time ranges between 20-30 minutes.
{% data reusables.enterprise_installation.promoting-a-replica %}
1. Se o dispositivo primário estiver disponível, para permitir que a replicação seja concluída antes de você alternar os dispositivos, no dispositivo primário, coloque o dispositivo primário no modo de manutenção.
1. If the primary appliance is available, to allow replication to finish before you switch appliances, on the primary appliance, put the primary appliance into maintenance mode.
- Coloque o dispositivo no modo de manutenção.
- Put the appliance into maintenance mode.
- Para usar o console de gerenciamento, confira "[Como habilitar e agendar o modo de manutenção](/enterprise/admin/guides/installation/enabling-and-scheduling-maintenance-mode/)"
- To use the management console, see "[Enabling and scheduling maintenance mode](/enterprise/admin/guides/installation/enabling-and-scheduling-maintenance-mode/)"
- Use também o comando `ghe-maintenance -s`.
- You can also use the `ghe-maintenance -s` command.
```shell
$ ghe-maintenance -s
```
- Quando o número de operações ativas do Git, consultas MySQL e tarefas do Resque alcançam zero, aguarde 30 segundos.
- When the number of active Git operations, MySQL queries, and Resque jobs reaches zero, wait 30 seconds.
{% note %}
**Observação:** o Nomad sempre terá trabalhos em execução, mesmo no modo de manutenção, ou seja, você pode ignorar esses trabalhos com segurança.
**Note:** Nomad will always have jobs running, even in maintenance mode, so you can safely ignore these jobs.
{% endnote %}
- Para verificar se todos os canais de replicação relatam `OK`, use o comando `ghe-repl-status -vv`.
- To verify all replication channels report `OK`, use the `ghe-repl-status -vv` command.
```shell
$ ghe-repl-status -vv
```
4. No dispositivo de réplica, para interromper a replicação e promover o dispositivo de réplica ao status primário, use o comando `ghe-repl-promote`. A ação também colocará automaticamente o nó primário no nó de manutenção, se ele for acessível.
4. On the replica appliance, to stop replication and promote the replica appliance to primary status, use the `ghe-repl-promote` command. This will also automatically put the primary node in maintenance mode if its reachable.
```shell
$ ghe-repl-promote
```
5. Atualize o registro DNS para apontar para o endereço IP do appliance réplica. O tráfego é direcionado para o réplica após o término do período TTL. Se você estiver usando um balanceador de carga, verifique se ele está configurado para enviar tráfego para o réplica.
6. Avise aos usuários que eles podem voltar a trabalhar normalmente.
7. Se desejar, configure a replicação do novo primário para os appliances existentes e o primário anterior. Para obter mais informações, confira "[Sobre a configuração de alta disponibilidade](/enterprise/admin/guides/installation/about-high-availability-configuration/#utilities-for-replication-management)".
8. Appliances para os quais você não pretende configurar replicação faziam parte da configuração de alta disponibilidade antes da falha precisam ser removidos da configuração de alta disponibilidade por UUID.
- Nos dispositivos anteriores, obtenha o UUID por meio de `cat /data/user/common/uuid`.
{% note %}
**Note:** If the primary node is unavailable, warnings and timeouts may occur but can be ignored.
{% endnote %}
5. Update the DNS record to point to the IP address of the replica. Traffic is directed to the replica after the TTL period elapses. If you are using a load balancer, ensure it is configured to send traffic to the replica.
6. Notify users that they can resume normal operations.
7. If desired, set up replication from the new primary to existing appliances and the previous primary. For more information, see "[About high availability configuration](/enterprise/admin/guides/installation/about-high-availability-configuration/#utilities-for-replication-management)."
8. Appliances you do not intend to setup replication to that were part of the high availability configuration prior the failover, need to be removed from the high availability configuration by UUID.
- On the former appliances, get their UUID via `cat /data/user/common/uuid`.
```shell
$ cat /data/user/common/uuid
```
- No novo primário, remova os UUIDs usando `ghe-repl-teardown`. Substitua *`UUID`* por um UUID recuperado na etapa anterior.
- On the new primary, remove the UUIDs using `ghe-repl-teardown`. Please replace *`UUID`* with a UUID you retrieved in the previous step.
```shell
$ ghe-repl-teardown -u <em>UUID</em>
$ ghe-repl-teardown -u UUID
```
## <a name="further-reading"></a>Leitura adicional
## Further reading
- "[Utilitários para o gerenciamento de replicações](/enterprise/admin/guides/installation/about-high-availability-configuration/#utilities-for-replication-management)"
- "[Utilities for replication management](/enterprise/admin/guides/installation/about-high-availability-configuration/#utilities-for-replication-management)"

Просмотреть файл

@ -117,11 +117,11 @@ For more information about the audit log REST API, see "[Enterprise administrati
### Example 1: All events in an enterprise, for a specific date, with pagination
You can use page-based pagination or cursor based pagination. For more information, see "[Traversing with Pagination](/rest/guides/traversing-with-pagination)."
You can use page-based pagination or cursor based pagination. For more information about pagination, see "[Using pagination in the REST API](/rest/guides/using-pagination-in-the-rest-api)."
#### Example with page-based pagination
The query below searches for audit log events created on Jan 1st, 2022 in the `avocado-corp` enterprise, and return the first page with a maximum of 100 items per page using [REST API pagination](/rest/overview/resources-in-the-rest-api#pagination):
The query below searches for audit log events created on Jan 1st, 2022 in the `avocado-corp` enterprise, and return the first page with a maximum of 100 items per page using pagination. For more information about pagination, see "[Using pagination in the REST API](/rest/guides/using-pagination-in-the-rest-api)."
```shell
curl -H "Authorization: Bearer TOKEN" \
@ -131,7 +131,7 @@ curl -H "Authorization: Bearer TOKEN" \
#### Example with cursor-based pagination
The query below searches for audit log events created on Jan 1st, 2022 in the `avocado-corp` enterprise, and returns the first page with a maximum of 100 items per page using [REST API pagination](/rest/overview/resources-in-the-rest-api#pagination). The `--include` flag causes the headers to be returned along with the response.
The query below searches for audit log events created on Jan 1st, 2022 in the `avocado-corp` enterprise, and returns the first page with a maximum of 100 items per page using pagination. For more information about pagination, see "[Using pagination in the REST API](/rest/guides/using-pagination-in-the-rest-api)." The `--include` flag causes the headers to be returned along with the response.
```
curl --include -H "Authorization: Bearer TOKEN" \

Просмотреть файл

@ -26,7 +26,7 @@ topics:
If your project communicates with an external service, you might use a token or private key for authentication. Tokens and private keys are examples of secrets that a service provider can issue. If you check a secret into a repository, anyone who has read access to the repository can use the secret to access the external service with your privileges. We recommend that you store secrets in a dedicated, secure location outside of the repository for your project.
{% data variables.product.prodname_secret_scanning_caps %} will scan your entire Git history on all branches present in your {% data variables.product.prodname_dotcom %} repository for secrets{% ifversion ghec or ghes > 3.4 or ghae > 3.4 %}, even if the repository is archived{% endif %}.
{% data variables.product.prodname_secret_scanning_caps %} will scan your entire Git history on all branches present in your {% data variables.product.prodname_dotcom %} repository for secrets{% ifversion ghec or ghes > 3.4 or ghae > 3.4 %}, even if the repository is archived{% endif %}. {% ifversion secret-scanning-issue-body-comments %}{% data reusables.secret-scanning.scan-issue-description-and-comments %}{% endif %}
{% ifversion fpt or ghec %}
{% data variables.product.prodname_secret_scanning_caps %} is available on {% data variables.product.prodname_dotcom_the_website %} in two forms:
@ -46,7 +46,7 @@ You can also enable {% data variables.product.prodname_secret_scanning %} as a p
{% ifversion fpt or ghec %}
## About {% data variables.product.prodname_secret_scanning_partner %}
When you make a repository public, or push changes to a public repository, {% data variables.product.product_name %} always scans the code for secrets that match partner patterns. If {% data variables.product.prodname_secret_scanning %} detects a potential secret, we notify the service provider who issued the secret. The service provider validates the string and then decides whether they should revoke the secret, issue a new secret, or contact you directly. Their action will depend on the associated risks to you or them. For more information, see "[Supported secrets for partner patterns](/code-security/secret-scanning/secret-scanning-patterns#supported-secrets-for-partner-patterns)."
When you make a repository public, or push changes to a public repository, {% data variables.product.product_name %} always scans the code for secrets that match partner patterns. {% ifversion secret-scanning-issue-body-comments %}{% data reusables.secret-scanning.scan-issue-description-and-comments %}{% endif %} If {% data variables.product.prodname_secret_scanning %} detects a potential secret, we notify the service provider who issued the secret. The service provider validates the string and then decides whether they should revoke the secret, issue a new secret, or contact you directly. Their action will depend on the associated risks to you or them. For more information, see "[Supported secrets for partner patterns](/code-security/secret-scanning/secret-scanning-patterns#supported-secrets-for-partner-patterns)."
You cannot change the configuration of {% data variables.product.prodname_secret_scanning %} on public repositories.
@ -68,7 +68,15 @@ You cannot change the configuration of {% data variables.product.prodname_secret
## About {% data variables.product.prodname_secret_scanning %} on {% data variables.product.product_name %}
{% endif %}
{% data variables.product.prodname_secret_scanning_GHAS_caps %} is available on all organization-owned repositories as part of {% data variables.product.prodname_GH_advanced_security %}. It is not available on user-owned repositories. When you enable {% data variables.product.prodname_secret_scanning %} for a repository, {% data variables.product.prodname_dotcom %} scans the code for patterns that match secrets used by many service providers. {% ifversion secret-scanning-backfills %}{% data variables.product.prodname_dotcom %} will also periodically run a full git history scan of existing content in {% data variables.product.prodname_GH_advanced_security %} repositories where {% data variables.product.prodname_secret_scanning %} is enabled, and send alert notifications following the {% data variables.product.prodname_secret_scanning %} alert notification settings. {% endif %}For more information, see "{% ifversion ghec %}[Supported secrets for advanced security](/code-security/secret-scanning/secret-scanning-patterns#supported-secrets-for-advanced-security){% else %}[{% data variables.product.prodname_secret_scanning_caps %} patterns](/code-security/secret-scanning/secret-scanning-patterns){% endif %}."
{% data variables.product.prodname_secret_scanning_GHAS_caps %} is available on all organization-owned repositories as part of {% data variables.product.prodname_GH_advanced_security %}. It is not available on user-owned repositories. When you enable {% data variables.product.prodname_secret_scanning %} for a repository, {% data variables.product.prodname_dotcom %} scans the code for patterns that match secrets used by many service providers. {% ifversion secret-scanning-issue-body-comments %}{% data reusables.secret-scanning.scan-issue-description-and-comments %}{% endif %} {% ifversion secret-scanning-backfills %}{% data variables.product.prodname_dotcom %} will also periodically run a full git history scan of existing content in {% data variables.product.prodname_GH_advanced_security %} repositories where {% data variables.product.prodname_secret_scanning %} is enabled, and send alert notifications following the {% data variables.product.prodname_secret_scanning %} alert notification settings. {% endif %}For more information, see "{% ifversion ghec %}[Supported secrets for advanced security](/code-security/secret-scanning/secret-scanning-patterns#supported-secrets-for-advanced-security){% else %}[{% data variables.product.prodname_secret_scanning_caps %} patterns](/code-security/secret-scanning/secret-scanning-patterns){% endif %}."
{% ifversion secret-scanning-issue-body-comments %}
{% note %}
**Note:** {% data variables.product.prodname_secret_scanning_caps %} for issue descriptions and comments is in public beta and subject to change.
{% endnote %}
{% endif %}
If you're a repository administrator you can enable {% data variables.product.prodname_secret_scanning_GHAS %} for any repository{% ifversion ghec or ghes > 3.4 or ghae > 3.4 %}, including archived repositories{% endif %}. Organization owners can also enable {% data variables.product.prodname_secret_scanning_GHAS %} for all repositories or for all new repositories within an organization. For more information, see "[Managing security and analysis settings for your repository](/github/administering-a-repository/managing-security-and-analysis-settings-for-your-repository)" and "[Managing security and analysis settings for your organization](/organizations/keeping-your-organization-secure/managing-security-and-analysis-settings-for-your-organization)."
@ -80,7 +88,7 @@ If you're a repository administrator you can enable {% data variables.product.pr
### About {% data variables.product.prodname_secret_scanning %} alerts
When you enable {% data variables.product.prodname_secret_scanning %} for a repository or push commits to a repository with {% data variables.product.prodname_secret_scanning %} enabled, {% data variables.product.prodname_dotcom %} scans the contents of those commits for secrets that match patterns defined by service providers{% ifversion ghes or ghae or ghec %} and any custom patterns defined in your enterprise, organization, or repository{% endif %}. {% ifversion secret-scanning-backfills %}{% data variables.product.prodname_dotcom %} also periodically runs a scan of all historical content in repositories with {% data variables.product.prodname_secret_scanning %} enabled.{% endif%}
When you enable {% data variables.product.prodname_secret_scanning %} for a repository or push commits to a repository with {% data variables.product.prodname_secret_scanning %} enabled, {% data variables.product.prodname_dotcom %} scans the contents of those commits for secrets that match patterns defined by service providers{% ifversion ghes or ghae or ghec %} and any custom patterns defined in your enterprise, organization, or repository{% endif %}. {% ifversion secret-scanning-issue-body-comments %}{% data reusables.secret-scanning.scan-issue-description-and-comments %}{% endif %} {% ifversion secret-scanning-backfills %}{% data variables.product.prodname_dotcom %} also periodically runs a scan of all historical content in repositories with {% data variables.product.prodname_secret_scanning %} enabled.{% endif%}
If {% data variables.product.prodname_secret_scanning %} detects a secret, {% data variables.product.prodname_dotcom %} generates an alert.

Просмотреть файл

@ -24,7 +24,14 @@ shortTitle: Configure secret scans
## Enabling {% data variables.product.prodname_secret_scanning_GHAS %}
You can enable {% data variables.product.prodname_secret_scanning_GHAS %} for any repository that is owned by an organization. Once enabled, {% data reusables.secret-scanning.secret-scanning-process %}
You can enable {% data variables.product.prodname_secret_scanning_GHAS %} for any repository that is owned by an organization. Once enabled, {% data reusables.secret-scanning.secret-scanning-process %} {% ifversion secret-scanning-issue-body-comments %}{% data reusables.secret-scanning.scan-issue-description-and-comments %}
{% note %}
**Note:** {% data variables.product.prodname_secret_scanning_caps %} for issue descriptions and comments is in public beta and subject to change.
{% endnote %}
{% endif %}
{% ifversion secret-scanning-enterprise-level %}
{% note %}
@ -37,14 +44,14 @@ You can enable {% data variables.product.prodname_secret_scanning_GHAS %} for an
{% data reusables.repositories.navigate-to-repo %}
{% data reusables.repositories.sidebar-settings %}
{% data reusables.repositories.navigate-to-code-security-and-analysis %}
4. If {% data variables.product.prodname_advanced_security %} is not already enabled for the repository, to the right of "{% data variables.product.prodname_GH_advanced_security %}", click **Enable**.
1. If {% data variables.product.prodname_advanced_security %} is not already enabled for the repository, to the right of "{% data variables.product.prodname_GH_advanced_security %}", click **Enable**.
{% ifversion fpt or ghec %}![Enable {% data variables.product.prodname_GH_advanced_security %} for your repository](/assets/images/help/repository/enable-ghas-dotcom.png)
{% elsif ghes or ghae %}![Enable {% data variables.product.prodname_GH_advanced_security %} for your repository](/assets/images/enterprise/3.1/help/repository/enable-ghas.png){% endif %}
5. Review the impact of enabling {% data variables.product.prodname_advanced_security %}, then click **Enable {% data variables.product.prodname_GH_advanced_security %} for this repository**.
6. When you enable {% data variables.product.prodname_advanced_security %}, {% data variables.product.prodname_secret_scanning %} may automatically be enabled for the repository due to the organization's settings. If "{% data variables.product.prodname_secret_scanning_caps %}" is shown with an **Enable** button, you still need to enable {% data variables.product.prodname_secret_scanning %} by clicking **Enable**. If you see a **Disable** button, {% data variables.product.prodname_secret_scanning %} is already enabled.
2. Review the impact of enabling {% data variables.product.prodname_advanced_security %}, then click **Enable {% data variables.product.prodname_GH_advanced_security %} for this repository**.
3. When you enable {% data variables.product.prodname_advanced_security %}, {% data variables.product.prodname_secret_scanning %} may automatically be enabled for the repository due to the organization's settings. If "{% data variables.product.prodname_secret_scanning_caps %}" is shown with an **Enable** button, you still need to enable {% data variables.product.prodname_secret_scanning %} by clicking **Enable**. If you see a **Disable** button, {% data variables.product.prodname_secret_scanning %} is already enabled.
![Enable {% data variables.product.prodname_secret_scanning %} for your repository](/assets/images/help/repository/enable-secret-scanning-dotcom.png)
{% ifversion secret-scanning-push-protection %}
7. Optionally, if you want to enable push protection, click **Enable** to the right of "Push protection." {% data reusables.secret-scanning.push-protection-overview %} For more information, see "[Protecting pushes with {% data variables.product.prodname_secret_scanning %}](/code-security/secret-scanning/protecting-pushes-with-secret-scanning)."
1. Optionally, if you want to enable push protection, click **Enable** to the right of "Push protection." {% data reusables.secret-scanning.push-protection-overview %} For more information, see "[Protecting pushes with {% data variables.product.prodname_secret_scanning %}](/code-security/secret-scanning/protecting-pushes-with-secret-scanning)."
![Enable push protection for your repository](/assets/images/help/repository/secret-scanning-enable-push-protection.png)
{% endif %}
{% ifversion ghae %}

Просмотреть файл

@ -31,8 +31,13 @@ After you enable SCIM, the following provisioning features are available for any
Alternatively, you can configure SAML SSO for an enterprise using Okta. SCIM for enterprise accounts is only available with Enterprise Managed Users. For more information, see "[Configuring SAML single sign-on for your enterprise using Okta](/admin/identity-and-access-management/managing-iam-for-your-enterprise/configuring-saml-single-sign-on-for-your-enterprise-using-okta)" and "[Configuring SCIM provisioning for Enterprise Managed Users with Okta](/admin/identity-and-access-management/managing-iam-with-enterprise-managed-users/configuring-scim-provisioning-for-enterprise-managed-users-with-okta)."
## Adding the {% data variables.product.prodname_ghe_cloud %} application in Okta
## Configuring SAML in Okta
{% data reusables.saml.okta-ae-applications-menu %}
{% data reusables.saml.okta-browse-app-catalog %}
{% data reusables.saml.okta-add-ghec-org-integration %}
1. Fill out the form, providing the name of your organization on {% data variables.product.prodname_dotcom %} and a unique name for your OAuth App Integration application.
{% data reusables.saml.assign-yourself-to-okta %}
{% data reusables.saml.okta-sign-on-tab %}
{% data reusables.saml.okta-view-setup-instructions %}
1. Enable and test SAML SSO on {% data variables.product.prodname_dotcom %} using the sign on URL, issuer URL, and public certificates from the "How to Configure SAML 2.0" guide. For more information, see "[Enabling and testing SAML single sign-on for your organization](/organizations/managing-saml-single-sign-on-for-your-organization/enabling-and-testing-saml-single-sign-on-for-your-organization#enabling-and-testing-saml-single-sign-on-for-your-organization)."

Просмотреть файл

@ -18,7 +18,7 @@ children:
- /delivering-deployments
- /rendering-data-as-graphs
- /working-with-comments
- /traversing-with-pagination
- /using-pagination-in-the-rest-api
- /building-a-ci-server
- /best-practices-for-integrators
- /getting-started-with-the-git-database-api

Просмотреть файл

@ -1,350 +0,0 @@
---
title: Traversing with pagination
intro: Explore how to use pagination to manage your responses with some examples using the Search API.
redirect_from:
- /guides/traversing-with-pagination
- /v3/guides/traversing-with-pagination
versions:
fpt: '*'
ghes: '*'
ghae: '*'
ghec: '*'
topics:
- API
shortTitle: Traverse with pagination
miniTocMaxHeadingLevel: 3
---
The {% ifversion fpt or ghec %}{% data variables.product.prodname_dotcom %}{% else %}{% data variables.product.product_name %}{% endif %} API provides a vast wealth of information for developers to consume.
Most of the time, you might even find that you're asking for _too much_ information,
and in order to keep our servers happy, the API will automatically [paginate the requested items](/rest/overview/resources-in-the-rest-api#pagination).
In this guide, we'll make some calls to the Search API, and iterate over
the results using pagination. You can find the complete source code for this project
in the [platform-samples][platform samples] repository.
{% data reusables.rest-api.dotcom-only-guide-note %}
## Basics of Pagination
To start with, it's important to know a few facts about receiving paginated items:
1. Different API calls respond with different defaults. For example, a call to
[List public repositories](/rest/reference/repos#list-public-repositories)
provides paginated items in sets of 30, whereas a call to the GitHub Search API
provides items in sets of 100
2. You can specify how many items to receive (up to a maximum of 100); but,
3. For technical reasons, not every endpoint behaves the same. For example,
[events](/rest/reference/activity#events) won't let you set a maximum for items to receive.
Be sure to read the documentation on how to handle paginated results for specific endpoints.
{% note %}
**Note**: You should always rely on URLs included in the link header. Don't try to guess or construct your own URLs.
{% endnote %}
### Link header
The response header includes information about pagination. For more information about headers, see "[Getting started with the REST API](/rest/guides/getting-started-with-the-rest-api#about-the-response-code-and-headers)." To get the response header, include the `-I` flag in your request. For example:
```shell
$ curl -I -H "Accept: application/vnd.github+json" -H "Authorization: Bearer YOUR_TOKEN" https://api.github.com/enterprises/advacado-corp/audit-log
```
The `-I` flag returns only the response header. If the response is paginated, the response header will include a `link` header. The header will look something like this:
```
link: <https://api.github.com/enterprises/13827/audit-log?after=MS42NjQzODM5MTkzNDdlKzEyfDM0MkI6NDdBNDo4RTFGMEM6NUIyQkZCMzo2MzM0N0JBRg%3D%3D&before=>; rel="next"
```
or
```
link: <https://api.github.com/repositories/1300192/issues?page=2>; rel="next", <https://api.github.com/repositories/1300192/issues?page=511>; rel="last"
```
### Types of pagination
{% data variables.product.company_short %}'s API uses two pagination methods: page-based pagination and cursor-based pagination. If the `link` header includes `page`, then the operation uses page-based pagination. If the `link` header includes `before` and `after`, then the operation uses cursor-based pagination.
#### Page based pagination
The link header for page-based pagination will tell you information about the previous, next, first, and last pages. If you did not request a specific page, then the response will default to the first page and information about the first and previous pages will be omitted.
For example, for a request that did not specify a page, this header states that the next page is `2` and the last page is `511`.
```
link: <https://api.github.com/repositories/1300192/issues?page=2>; rel="next", <https://api.github.com/repositories/1300192/issues?page=511>; rel="last"
```
For example, for a request that specified page 5, this header states that the previous page is `4`, the next page is `6`, the last page is `511`, and the first page is `1`.
```
link: <https://api.github.com/repositories/1300192/issues?page=4>; rel="prev", <https://api.github.com/repositories/1300192/issues?page=6>; rel="next", <https://api.github.com/repositories/1300192/issues?page=511>; rel="last", <https://api.github.com/repositories/1300192/issues?page=1>; rel="first"
```
#### Cursor based pagination
Cursor pagination uses terms `before` and `after` in order to navigate through pages. `rel="next"` and `rel="prev"` this mark the cursor point in the data set and provides a reference for traveling to the page `before` and `after` the current page.
```
link: <https://api.github.com/enterprises/13827/audit-log?after=MS42NjQzODMzMzk2MzZlKzEyfFdxSzIxdGU0MlBWNUp5UzhBWDF6LWc%3D&before=>; rel="next",
<https://api.github.com/enterprises/13827/audit-log?after=&before=>; rel="first",
<https://api.github.com/enterprises/13827/audit-log?after=&before=MS42NjQzODM5MTcyMjllKzEyfDI4NDE6NEVFNDoxODBDRkM5OjY5REE0MzI6NjMzNDdCQUQ%3D>; rel="prev"
```
In this example, `rel=next` says that the next page is located at:
```
after=MS42NjQzODM5MTkzNDdlKzEyfDM0MkI6NDdBNDo4RTFGMEM6NUIyQkZCMzo2MzM0N0JBRg%3D%3D&before=
```
### Using pagination
#### Cursor based pagination
Using cursor based pagination requires you to use the terms `before` and `after`. To navigate using `before` and `after`, copy the link header generated above into your curl request:
```shell
$ curl -I -H "Accept: application/vnd.github+json" -H "Authorization: Bearer YOUR_TOKEN" https://api.github.com/enterprises/13827/audit-log?after=MS42NjQzODM5MTkzNDdlKzEyfDM0MkI6NDdBNDo4RTFGMEM6NUIyQkZCMzo2MzM0N0JBRg%3D%3D&before=
```
The above example will generate a page of results and new header information that you can use to make the next request. `rel="next"` provides the next page of results. `rel="prev"` provides the previous page of results. The important part of the output here is the link header needs to be generated rather than manually imputed. Copy the entire link from the following output.
```
link: <https://api.github.com/enterprises/13827/audit-log?after=MS42NjQzODMzMzk2MzZlKzEyfFdxSzIxdGU0MlBWNUp5UzhBWDF6LWc%3D&before=>; rel="next",
<https://api.github.com/enterprises/13827/audit-log?after=&before=>; rel="first",
<https://api.github.com/enterprises/13827/audit-log?after=&before=MS42NjQzODM5MTcyMjllKzEyfDI4NDE6NEVFNDoxODBDRkM5OjY5REE0MzI6NjMzNDdCQUQ%3D>; rel="prev"
```
Unlike page-based pagination, the results will not return the last page number in the response.
link: <https://api.github.com/enterprises/13827/audit-log?after=MS42NjQzODMzMzk2MzZlKzEyfFdxSzIxdGU0MlBWNUp5UzhBWDF6LWc%3D&before=>; rel="next",
<https://api.github.com/enterprises/13827/audit-log?after=&before=>; rel="first",
<https://api.github.com/enterprises/13827/audit-log?after=&before=MS42NjQzODM5MTcyMjllKzEyfDI4NDE6NEVFNDoxODBDRkM5OjY5REE0MzI6NjMzNDdCQUQ%3D>; rel="prev"
Because cursor based pagination creates a reference point in the data set, it cannot calculate the total number of results.
#### Page based pagination
To navigate using page based pagination pass in a `page`
parameter. By default, `page` always starts at `1`. In the following example, we have made a curl request to the search API Mozilla projects use the phrase `addClass`. Instead of starting at 1, lets jump to page 14.
```shell
$ curl -I "https://api.github.com/search/code?q=addClass+user:mozilla&page=14"
```
Here's an except of the link header in the HTTP request:
Link: <https://api.github.com/search/code?q=addClass+user%3Amozilla&page=15>; rel="next",
<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=34>; rel="last",
<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=1>; rel="first",
<https://api.github.com/search/code?q=addClass+user%3Amozilla&page=13>; rel="prev"
In this example, `rel="next"` is at 15, and `rel="last"` is 34. But now we've
got some more information: `rel="first"` indicates the URL for the _first_ page,
and more importantly, `rel="prev"` lets you know the page number of the previous
page. Using this information, you could construct some UI that lets users jump
between the first, previous, next, or last list of results in an API call.
### Changing the number of items received
#### Page based pagination
By passing the `per_page` parameter, you can specify how many items you want
each page to return, up to 100 items. Let's try asking for 50 items about `addClass`:
```shell
$ curl -I "https://api.github.com/search/code?q=addClass+user:mozilla&per_page=50"
```
Notice what it does to the header response:
Link: <https://api.github.com/search/code?q=addClass+user%3Amozilla&per_page=50&page=2>; rel="next",
<https://api.github.com/search/code?q=addClass+user%3Amozilla&per_page=50&page=20>; rel="last"
As you might have guessed, the `rel="last"` information says that the last page
is now 20. This is because we are asking for more information per page about
our results.
#### Cursor based pagination
You can also pass the `per_page` parameter for cursor-based pagination.
```shell
$ curl -I -H "Accept: application/vnd.github+json" -H "Authorization: Bearer YOUR_TOKEN" https://api.github.com/enterprises/13827/audit-log?after=MS42NjQzODM5MTkzNDdlKzEyfDM0MkI6NDdBNDo4RTFGMEM6NUIyQkZCMzo2MzM0N0JBRg%3D%3D&before=&per_page=50
```
## Consuming the information
You don't want to be making low-level curl calls just to be able to work with
pagination, so let's write a little Ruby script that does everything we've
just described above.
As always, first we'll require [GitHub's Octokit.rb][octokit.rb] Ruby library, and
pass in our [{% data variables.product.pat_generic %}][personal token]:
``` ruby
require 'octokit'
# !!! DO NOT EVER USE HARD-CODED VALUES IN A REAL APP !!!
# Instead, set and test environment variables, like below
client = Octokit::Client.new :access_token => ENV['MY_PERSONAL_TOKEN']
```
Next, we'll execute the search, using Octokit's `search_code` method. Unlike
using `curl`, we can also immediately retrieve the number of results, so let's
do that:
``` ruby
results = client.search_code('addClass user:mozilla')
total_count = results.total_count
```
Now, let's grab the number of the last page, similar to `page=34>; rel="last"`
information in the link header. Octokit.rb support pagination information through
an implementation called "[Hypermedia link relations][hypermedia-relations]."
We won't go into detail about what that is, but, suffice to say, each element
in the `results` variable has a hash called `rels`, which can contain information
about `:next`, `:last`, `:first`, and `:prev`, depending on which result you're
on. These relations also contain information about the resulting URL, by calling
`rels[:last].href`.
Knowing this, let's grab the page number of the last result, and present all
this information to the user:
``` ruby
last_response = client.last_response
number_of_pages = last_response.rels[:last].href.match(/page=(\d+).*$/)[1]
puts "There are #{total_count} results, on #{number_of_pages} pages!"
```
Finally, let's iterate through the results. You could do this with a loop `for i in 1..number_of_pages.to_i`,
but instead, let's follow the `rels[:next]` headers to retrieve information from
each page. For the sake of simplicity, let's just grab the file path of the first
result from each page. To do this, we'll need a loop; and at the end of every loop,
we'll retrieve the data set for the next page by following the `rels[:next]` information.
The loop will finish when there is no `rels[:next]` information to consume (in other
words, we are at `rels[:last]`). It might look something like this:
``` ruby
puts last_response.data.items.first.path
until last_response.rels[:next].nil?
last_response = last_response.rels[:next].get
puts last_response.data.items.first.path
end
```
Changing the number of items per page is extremely simple with Octokit.rb. Simply
pass a `per_page` options hash to the initial client construction. After that,
your code should remain intact:
``` ruby
require 'octokit'
# !!! DO NOT EVER USE HARD-CODED VALUES IN A REAL APP !!!
# Instead, set and test environment variables, like below
client = Octokit::Client.new :access_token => ENV['MY_PERSONAL_TOKEN']
results = client.search_code('addClass user:mozilla', :per_page => 100)
total_count = results.total_count
last_response = client.last_response
number_of_pages = last_response.rels[:last].href.match(/page=(\d+).*$/)[1]
puts last_response.rels[:last].href
puts "There are #{total_count} results, on #{number_of_pages} pages!"
puts "And here's the first path for every set"
puts last_response.data.items.first.path
until last_response.rels[:next].nil?
last_response = last_response.rels[:next].get
puts last_response.data.items.first.path
end
```
## Constructing Pagination Links
Normally, with pagination, your goal isn't to concatenate all of the possible
results, but rather, to produce a set of navigation, like this:
![Sample of pagination links](/assets/images/pagination_sample.png)
Let's sketch out a micro-version of what that might entail.
From the code above, we already know we can get the `number_of_pages` in the
paginated results from the first call:
``` ruby
require 'octokit'
# !!! DO NOT EVER USE HARD-CODED VALUES IN A REAL APP !!!
# Instead, set and test environment variables, like below
client = Octokit::Client.new :access_token => ENV['MY_PERSONAL_TOKEN']
results = client.search_code('addClass user:mozilla')
total_count = results.total_count
last_response = client.last_response
number_of_pages = last_response.rels[:last].href.match(/page=(\d+).*$/)[1]
puts last_response.rels[:last].href
puts "There are #{total_count} results, on #{number_of_pages} pages!"
```
From there, we can construct a beautiful ASCII representation of the number boxes:
``` ruby
numbers = ""
for i in 1..number_of_pages.to_i
numbers << "[#{i}] "
end
puts numbers
```
Let's simulate a user clicking on one of these boxes, by constructing a random
number:
``` ruby
random_page = Random.new
random_page = random_page.rand(1..number_of_pages.to_i)
puts "A User appeared, and clicked number #{random_page}!"
```
Now that we have a page number, we can use Octokit to explicitly retrieve that
individual page, by passing the `:page` option:
``` ruby
clicked_results = client.search_code('addClass user:mozilla', :page => random_page)
```
If we wanted to get fancy, we could also grab the previous and next pages, in
order to generate links for back (`<<`) and forward (`>>`) elements:
``` ruby
prev_page_href = client.last_response.rels[:prev] ? client.last_response.rels[:prev].href : "(none)"
next_page_href = client.last_response.rels[:next] ? client.last_response.rels[:next].href : "(none)"
puts "The prev page link is #{prev_page_href}"
puts "The next page link is #{next_page_href}"
```
[pagination]: /rest#pagination
[platform samples]: https://github.com/github/platform-samples/tree/master/api/ruby/traversing-with-pagination
[octokit.rb]: https://github.com/octokit/octokit.rb
[personal token]: /articles/creating-an-access-token-for-command-line-use
[hypermedia-relations]: https://github.com/octokit/octokit.rb#pagination
[listing commits]: /rest/reference/commits#list-commits

Просмотреть файл

@ -10,6 +10,7 @@ featuredLinks:
- /rest/guides/getting-started-with-the-rest-api
- /rest/guides/basics-of-authentication
- /rest/guides/best-practices-for-integrators
- /rest/guides/using-pagination-in-the-rest-api
popular:
- /rest/overview/resources-in-the-rest-api
- /rest/overview/api-versions

Просмотреть файл

@ -1,6 +1,6 @@
---
title: Recursos na API REST
intro: 'Aprenda a navegar pelos recursos fornecidos pela API de {% ifversion fpt or ghec %}{% data variables.product.prodname_dotcom %}{% else %}{% data variables.product.product_name %}{% endif %}.'
title: Resources in the REST API
intro: 'Learn how to navigate the resources provided by the {% ifversion fpt or ghec %}{% data variables.product.prodname_dotcom %}{% else %}{% data variables.product.product_name %}{% endif %} API.'
redirect_from:
- /rest/initialize-the-repo
versions:
@ -11,23 +11,19 @@ versions:
miniTocMaxHeadingLevel: 3
topics:
- API
ms.openlocfilehash: 4fd3e2aad72ee0ffc4778a86dc99cd5bb6f9d2c5
ms.sourcegitcommit: 4daa156856e651cb3854ead40e35bd918e481ad6
ms.translationtype: HT
ms.contentlocale: pt-BR
ms.lasthandoff: 12/02/2022
ms.locfileid: '148190396'
---
{% ifversion api-date-versioning %}
## Versão da API
Os recursos disponíveis podem variar entre as versões da API REST. Você deve usar o cabeçalho `X-GitHub-Api-Version` para especificar uma versão da API. Para obter mais informações, confira "[Versões da API](/rest/overview/api-versions)".
{% ifversion api-date-versioning %}
## API version
Available resources may vary between REST API versions. You should use the `X-GitHub-Api-Version` header to specify an API version. For more information, see "[API Versions](/rest/overview/api-versions)."
{% endif %}
## Esquema
## Schema
{% ifversion fpt or ghec %}Todo o acesso à API é feito por HTTPS e{% else %}A API é{% endif %} acessada de `{% data variables.product.api_url_code %}`. Todos os dados são enviados e recebidos como JSON.
{% ifversion fpt or ghec %}All API access is over HTTPS, and{% else %}The API is{% endif %} accessed from `{% data variables.product.api_url_code %}`. All data is
sent and received as JSON.
```shell
$ curl -I {% data variables.product.api_url_pre %}/users/octocat/orgs
@ -48,45 +44,55 @@ $ curl -I {% data variables.product.api_url_pre %}/users/octocat/orgs
> X-Content-Type-Options: nosniff
```
Os campos em branco são incluídos como `null` em vez de serem omitidos.
Blank fields are included as `null` instead of being omitted.
Todos os timestamps são retornados no formato UTC, ISO 8601:
All timestamps return in UTC time, ISO 8601 format:
YYYY-MM-DDTHH:MM:SSZ
Para obter mais informações sobre fusos horários em carimbos de data/hora, confira [esta seção](#timezones).
For more information about timezones in timestamps, see [this section](#timezones).
### Apresentações resumidas
### Summary representations
Ao buscar uma lista de recursos, a resposta inclui um _subconjunto_ dos atributos para esse recurso. Esta é a representação "resumo" do recurso. (Alguns atributos são computacionalmente caros para a API fornecer.
Por razões de desempenho, a representação resumida exclui esses atributos.
Para obter esses atributos, busque a representação "detalhada".)
When you fetch a list of resources, the response includes a _subset_ of the
attributes for that resource. This is the "summary" representation of the
resource. (Some attributes are computationally expensive for the API to provide.
For performance reasons, the summary representation excludes those attributes.
To obtain those attributes, fetch the "detailed" representation.)
**Exemplo**: ao receber uma lista de repositórios, você recebe a representação resumida de cada repositório. Aqui, buscamos a lista de repositórios pertencentes à organização [octokit](https://github.com/octokit):
**Example**: When you get a list of repositories, you get the summary
representation of each repository. Here, we fetch the list of repositories owned
by the [octokit](https://github.com/octokit) organization:
GET /orgs/octokit/repos
### Representações detalhadas
### Detailed representations
Ao buscar um recurso individual, a resposta normalmente inclui _todos_ os atributos para esse recurso. Esta é a representação "detalhada" do recurso. (Observe que a autorização às vezes influencia a quantidade de detalhes incluídos na representação.)
When you fetch an individual resource, the response typically includes _all_
attributes for that resource. This is the "detailed" representation of the
resource. (Note that authorization sometimes influences the amount of detail
included in the representation.)
**Exemplo**: ao receber um repositório individual, você recebe a representação detalhada do repositório. Aqui, buscamos o repositório [octokit/octokit.rb](https://github.com/octokit/octokit.rb):
**Example**: When you get an individual repository, you get the detailed
representation of the repository. Here, we fetch the
[octokit/octokit.rb](https://github.com/octokit/octokit.rb) repository:
GET /repos/octokit/octokit.rb
A documentação fornece um exemplo de resposta para cada método da API. A resposta de exemplo ilustra todos os atributos que retornados por esse método.
The documentation provides an example response for each API method. The example
response illustrates all attributes that are returned by that method.
## Autenticação
## Authentication
{% ifversion ghae %} Recomendamos a autenticação na API REST {% data variables.product.product_name %} criando um token OAuth2 por meio do [fluxo do aplicativo Web](/developers/apps/authorizing-oauth-apps#web-application-flow). {% else %} Existem duas maneiras de efetuar a autenticação por meio da API REST de {% data variables.product.product_name %}.{% endif %} As solicitações que exigem autenticação retornarão `404 Not Found`, em vez de `403 Forbidden`, em alguns lugares. Isso é para evitar a fuga acidental de repositórios privados para usuários não autorizados.
{% ifversion ghae %} We recommend authenticating to the {% data variables.product.product_name %} REST API by creating an OAuth2 token through the [web application flow](/developers/apps/authorizing-oauth-apps#web-application-flow). {% else %} There are two ways to authenticate through {% data variables.product.product_name %} REST API.{% endif %} Requests that require authentication will return `404 Not Found`, instead of `403 Forbidden`, in some places. This is to prevent the accidental leakage of private repositories to unauthorized users.
### Autenticação Básica
### Basic authentication
```shell
$ curl -u "username" {% data variables.product.api_url_pre %}
```
### Token do OAuth2 (enviado em um cabeçalho)
### OAuth2 token (sent in a header)
```shell
$ curl -H "Authorization: Bearer OAUTH-TOKEN" {% data variables.product.api_url_pre %}
@ -94,17 +100,17 @@ $ curl -H "Authorization: Bearer OAUTH-TOKEN" {% data variables.product.api_url_
{% note %}
Observação: O GitHub recomenda enviar tokens do OAuth usando o cabeçalho de autorização.
Note: GitHub recommends sending OAuth tokens using the Authorization header.
{% endnote %}
{% note %}
**Observação:** {% data reusables.getting-started.bearer-vs-token %}
**Note:** {% data reusables.getting-started.bearer-vs-token %}
{% endnote %}
Leia [mais sobre OAuth2](/apps/building-oauth-apps/). Observe que os tokens OAuth2 podem ser adquiridos usando o [fluxo do aplicativo Web](/developers/apps/authorizing-oauth-apps#web-application-flow) para aplicativos de produção.
Read [more about OAuth2](/apps/building-oauth-apps/). Note that OAuth2 tokens can be acquired using the [web application flow](/developers/apps/authorizing-oauth-apps#web-application-flow) for production applications.
{% ifversion fpt or ghes or ghec %}
### OAuth2 key/secret
@ -115,20 +121,22 @@ Leia [mais sobre OAuth2](/apps/building-oauth-apps/). Observe que os tokens OAu
curl -u my_client_id:my_client_secret '{% data variables.product.api_url_pre %}/user/repos'
```
Usar seu `client_id` e `client_secret` _não_ autentica como usuário, apenas identificará seu aplicativo OAuth para aumentar seu limite de taxa. As permissões só são concedidas a usuários, não aplicativos, e você só obterá dados que um usuário não autenticado visualizaria. Por este motivo, você só deve usar a chave/segredo OAuth2 em cenários de servidor para servidor. Não deixe vazar o segredo do cliente do OAuth do seu aplicativo para os seus usuários.
Using your `client_id` and `client_secret` does _not_ authenticate as a user, it will only identify your OAuth App to increase your rate limit. Permissions are only granted to users, not applications, and you will only get back data that an unauthenticated user would see. For this reason, you should only use the OAuth2 key/secret in server-to-server scenarios. Don't leak your OAuth App's client secret to your users.
{% ifversion ghes %} Você não conseguirá efetuar a autenticação usando sua chave e segredo do OAuth2 enquanto estiver no modo privado e essa tentativa de autenticação irá retornar `401 Unauthorized`. Para obter mais informações, confira "[Como habilitar o modo privado](/admin/configuration/configuring-your-enterprise/enabling-private-mode)".
{% endif %} {% endif %}
{% ifversion ghes %}
You will be unable to authenticate using your OAuth2 key and secret while in private mode, and trying to authenticate will return `401 Unauthorized`. For more information, see "[Enabling private mode](/admin/configuration/configuring-your-enterprise/enabling-private-mode)".
{% endif %}
{% endif %}
{% ifversion fpt or ghec %}
Leia [mais sobre limite de taxa não autenticada](#increasing-the-unauthenticated-rate-limit-for-oauth-apps).
Read [more about unauthenticated rate limiting](#increasing-the-unauthenticated-rate-limit-for-oauth-apps).
{% endif %}
### Falha no limite de login
### Failed login limit
A autenticação com credenciais inválidas retornará `401 Unauthorized`:
Authenticating with invalid credentials will return `401 Unauthorized`:
```shell
$ curl -I {% data variables.product.api_url_pre %} -u foo:bar
@ -140,7 +148,9 @@ $ curl -I {% data variables.product.api_url_pre %} -u foo:bar
> }
```
Após detectar várias solicitações com credenciais inválidas em um curto período de tempo, a API rejeitará temporariamente todas as tentativas de autenticação para esse usuário (incluindo aquelas com credenciais válidas) com `403 Forbidden`:
After detecting several requests with invalid credentials within a short period,
the API will temporarily reject all authentication attempts for that user
(including ones with valid credentials) with `403 Forbidden`:
```shell
$ curl -i {% data variables.product.api_url_pre %} -u {% ifversion fpt or ghae or ghec %}
@ -152,55 +162,62 @@ $ curl -i {% data variables.product.api_url_pre %} -u {% ifversion fpt or ghae o
> }
```
## Parâmetros
## Parameters
Muitos métodos de API tomam parâmetros opcionais. Para solicitações tipo `GET`, todos os parâmetros não especificados como um segmento no caminho podem ser passados como um parâmetro de string de consulta de HTTP:
Many API methods take optional parameters. For `GET` requests, any parameters not
specified as a segment in the path can be passed as an HTTP query string
parameter:
```shell
$ curl -i "{% data variables.product.api_url_pre %}/repos/vmg/redcarpet/issues?state=closed"
```
Neste exemplo, os valores 'vmg' e 'redcarpet' são fornecidos para os parâmetros `:owner` e `:repo` no caminho, enquanto `:state` é passado na cadeia de caracteres de consulta.
In this example, the 'vmg' and 'redcarpet' values are provided for the `:owner`
and `:repo` parameters in the path while `:state` is passed in the query
string.
Para as solicitações `POST`, `PATCH`, `PUT` e `DELETE`, os parâmetros não incluídos na URL devem ser codificados como JSON com um tipo de conteúdo de 'application/json':
For `POST`, `PATCH`, `PUT`, and `DELETE` requests, parameters not included in the URL should be encoded as JSON
with a Content-Type of 'application/json':
```shell
$ curl -i -u username -d '{"scopes":["repo_deployment"]}' {% data variables.product.api_url_pre %}/authorizations
```
## Ponto de extremidade raiz
## Root endpoint
Você pode emitir uma solicitação `GET` para o ponto de extremidade de raiz para obter todas as categorias do ponto de extremidade com a qual a API REST é compatível:
You can issue a `GET` request to the root endpoint to get all the endpoint categories that the REST API supports:
```shell
$ curl {% ifversion fpt or ghae or ghec %}
-u USERNAME:TOKEN {% endif %}{% ifversion ghes %}-u USERNAME:PASSWORD {% endif %}{% data variables.product.api_url_pre %}
```
## IDs de nós globais do GraphQL
## GraphQL global node IDs
Confira o guia sobre "[Usar IDs de nós globais](/graphql/guides/using-global-node-ids)" para obter informações detalhadas sobre como localizar `node_id`s por meio da API REST e usá-los em operações do GraphQL.
See the guide on "[Using Global Node IDs](/graphql/guides/using-global-node-ids)" for detailed information about how to find `node_id`s via the REST API and use them in GraphQL operations.
## Erros do cliente
## Client errors
Há três tipos possíveis de erros de cliente em chamadas de API que recebem corpos de solicitação:
There are three possible types of client errors on API calls that
receive request bodies:
1. O envio de JSON inválido resultará em uma resposta `400 Bad Request`.
1. Sending invalid JSON will result in a `400 Bad Request` response.
HTTP/2 400
Content-Length: 35
{"message":"Problems parsing JSON"}
2. O envio do tipo errado de valores JSON resultará em uma resposta `400 Bad
Request`.
2. Sending the wrong type of JSON values will result in a `400 Bad
Request` response.
HTTP/2 400
Content-Length: 40
{"message":"Body should be a JSON object"}
3. O envio de campos inválidos resultará em uma resposta `422 Unprocessable Entity`.
3. Sending invalid fields will result in a `422 Unprocessable Entity`
response.
HTTP/2 422
Content-Length: 149
@ -216,49 +233,60 @@ Há três tipos possíveis de erros de cliente em chamadas de API que recebem co
]
}
Todos os objetos de erro têm propriedades de recursos e campos para que seu cliente possa dizer qual é o problema. Há também um código de erro para que você saiba o que está errado com o campo. Estes são os possíveis códigos de erro de validação:
All error objects have resource and field properties so that your client
can tell what the problem is. There's also an error code to let you
know what is wrong with the field. These are the possible validation error
codes:
Nome do código de erro | Descrição
Error code name | Description
-----------|-----------|
`missing` | Um recurso não existe.
`missing_field` | Não foi definido um campo obrigatório em um recurso.
`invalid` | Formatação de um campo é inválida. Revise a documentação para obter informações mais específicas.
`already_exists` | Outro recurso tem o mesmo valor que este campo. Isso pode acontecer em recursos que precisam ter alguma chave única (como nomes de etiqueta).
`unprocessable` | As entradas fornecidas eram inválidas.
`missing` | A resource does not exist.
`missing_field` | A required field on a resource has not been set.
`invalid` | The formatting of a field is invalid. Review the documentation for more specific information.
`already_exists` | Another resource has the same value as this field. This can happen in resources that must have some unique key (such as label names).
`unprocessable` | The inputs provided were invalid.
Os recursos também podem enviar erros de validação personalizados (em que `code` e `custom` ). Os erros personalizados sempre terão um campo de `message` que descreve o erro e a maioria dos erros também incluirá um campo de `documentation_url` que aponta para algum conteúdo que pode ajudá-lo a resolver o erro.
Resources may also send custom validation errors (where `code` is `custom`). Custom errors will always have a `message` field describing the error, and most errors will also include a `documentation_url` field pointing to some content that might help you resolve the error.
## Redirecionamentos HTTP
## HTTP redirects
A API REST do {% data variables.product.product_name %} usa o redirecionamento HTTP quando apropriado. Os clientes devem assumir que qualquer solicitação pode resultar em um redirecionamento. Receber um redirecionamento de HTTP *não* é um erro e os clientes devem seguir esse redirecionamento. As respostas de redirecionamento terão
um campo do cabeçalho do tipo `Location` que contém o URI do recurso ao qual o cliente deve repetir as solicitações.
The {% data variables.product.product_name %} REST API uses HTTP redirection where appropriate. Clients should assume that any
request may result in a redirection. Receiving an HTTP redirection is *not* an
error and clients should follow that redirect. Redirect responses will have a
`Location` header field which contains the URI of the resource to which the
client should repeat the requests.
Código de status | Descrição
Status Code | Description
-----------|-----------|
`301` | Redirecionamento permanente. O URI que você usou para fazer a solicitação foi substituído pelo especificado no campo do cabeçalho `Location`. Este e todas as solicitações futuras deste recurso devem ser direcionadas para o novo URI.
`302`, `307` | Redirecionamento temporário. A solicitação deve ser repetida literalmente para o URI especificado no campo de cabeçalho `Location`, mas os clientes devem continuar a usar o URI original para solicitações futuras.
`301` | Permanent redirection. The URI you used to make the request has been superseded by the one specified in the `Location` header field. This and all future requests to this resource should be directed to the new URI.
`302`, `307` | Temporary redirection. The request should be repeated verbatim to the URI specified in the `Location` header field but clients should continue to use the original URI for future requests.
Outros códigos de status de redirecionamento podem ser usados de acordo com a especificação HTTP 1.1.
Other redirection status codes may be used in accordance with the HTTP 1.1 spec.
## Verbos HTTP
## HTTP verbs
Sempre que possível, a API REST do {% data variables.product.product_name %} procura usar verbos HTTP apropriados para cada ação. Observe que os verbos HTTP diferenciam maiúsculas de minúsculas.
Where possible, the {% data variables.product.product_name %} REST API strives to use appropriate HTTP verbs for each
action. Note that HTTP verbs are case-sensitive.
Verbo | Descrição
Verb | Description
-----|-----------
`HEAD` | Pode ser emitido contra qualquer recurso para obter apenas as informações de cabeçalho HTTP.
`GET` | Usado para recuperar recursos.
`POST` | Usado para criar recursos.
`PATCH` | Usado para atualizar recursos com dados parciais do JSON. Por exemplo, um recurso de problema tem os atributos `title` e `body`. Uma solicitação de `PATCH` pode aceitar um ou mais dos atributos para atualizar o recurso.
`PUT` | Usado para substituir recursos ou coleções. Para solicitações `PUT` sem atributo `body`, defina o cabeçalho `Content-Length` como zero.
`DELETE` |Usado para excluir recursos.
`HEAD` | Can be issued against any resource to get just the HTTP header info.
`GET` | Used for retrieving resources.
`POST` | Used for creating resources.
`PATCH` | Used for updating resources with partial JSON data. For instance, an Issue resource has `title` and `body` attributes. A `PATCH` request may accept one or more of the attributes to update the resource.
`PUT` | Used for replacing resources or collections. For `PUT` requests with no `body` attribute, be sure to set the `Content-Length` header to zero.
`DELETE` |Used for deleting resources.
## Hipermídia
## Hypermedia
Todos os recursos podem ter uma ou mais propriedades `*_url` vinculando outros recursos. Estes tem o objetivo de fornecer URLs explícitas para que os clientes API apropriados não precisem construir URLs por conta própria. É altamente recomendável que os clientes da API
os utilizem. Fazer isso tornará as futuras atualizações da API mais fáceis para os desenvolvedores. Espera-se que todas as URLs sejam modelos de URI [RFC 6570][rfc] adequados.
All resources may have one or more `*_url` properties linking to other
resources. These are meant to provide explicit URLs so that proper API clients
don't need to construct URLs on their own. It is highly recommended that API
clients use these. Doing so will make future upgrades of the API easier for
developers. All URLs are expected to be proper [RFC 6570][rfc] URI templates.
Em seguida, você pode expandir esses modelos usando algo como ogem [uri_template][uri]:
You can then expand these templates using something like the [uri_template][uri]
gem:
>> tmpl = URITemplate.new('/notifications{?since,all,participating}')
>> tmpl.expand
@ -273,56 +301,13 @@ Em seguida, você pode expandir esses modelos usando algo como ogem [uri_templat
[rfc]: https://datatracker.ietf.org/doc/html/rfc6570
[uri]: https://github.com/hannesg/uri_template
## Paginação
## Pagination
Pedidos que retornam vários itens serão paginados para 30 itens por padrão. Você pode especificar mais páginas com o parâmetro `page`. Para alguns recursos, você também pode definir um tamanho de página até 100 com o parâmetro `per_page`.
Observe que por motivos técnicos nem todos os pontos de extremidade respeitam o parâmetro `per_page`, confira [eventos](/rest/reference/activity#events) por exemplo.
When a response from the REST API would include many results, {% data variables.product.company_short %} will paginate the results and return a subset of the results. You can use the link header from the response to request additional pages of data. If an endpoint supports the `per_page` query parameter, then you can control how many results are returned on a page. For more information about pagination, see "[Using pagination in the REST API](/rest/guides/using-pagination-in-the-rest-api)."
```shell
$ curl '{% data variables.product.api_url_pre %}/user/repos?page=2&per_page=100'
```
## Timeouts
Observe que a numeração da página é baseada em 1 e que, ao omitir o parâmetro `page`, retornará a primeira página.
Alguns pontos de extremidade usam paginação baseada no cursor. Um cursor é uma string que aponta para uma localização no conjunto de resultados.
Com paginação baseada em cursor, não há um conceito fixo de "páginas" no conjunto de resultados. Portanto, você não pode navegar para uma página específica.
Em vez disso, você pode percorrer os resultados usando os parâmetros `before` ou `after`.
Para obter mais informações sobre paginação, confira nosso guia sobre [Deslocamento com paginação][pagination-guide].
### Cabeçalho do link
{% note %}
**Observação:** É importante formar chamadas com valores de cabeçalho de link, em vez de construir suas URLs.
{% endnote %}
O [cabeçalho Link](https://datatracker.ietf.org/doc/html/rfc5988) inclui informações de paginação. Por exemplo:
Link: <{% data variables.product.api_url_code %}/user/repos?page=3&per_page=100>; rel="next",
<{% data variables.product.api_url_code %}/user/repos?page=50&per_page=100>; rel="last"
_O exemplo inclui uma quebra de linha para legibilidade._
Ou, se o ponto de extremidade usar paginação baseada em cursor:
Link: <{% data variables.product.api_url_code %}/orgs/ORG/audit-log?after=MTYwMTkxOTU5NjQxM3xZbGI4VE5EZ1dvZTlla09uWjhoZFpR&before=>; rel="next",
Esse cabeçalho de resposta `Link` contém uma ou mais relações de link de [Hipermídia](/rest#hypermedia), algumas das quais podem exigir expansão como [modelos de URI](https://datatracker.ietf.org/doc/html/rfc6570).
Os valores `rel` possíveis são:
Nome | Descrição
-----------|-----------|
`next` |A relação de link para a próxima página de resultados.
`last` |A relação de link para a última página de resultados.
`first` |A relação de link para a primeira página de resultados.
`prev` |A relação de link para a página de resultados anterior imediata.
## Tempos limite
Se {% data variables.product.prodname_dotcom %} leva mais de 10 segundos para processar uma solicitação de API, {% data variables.product.prodname_dotcom %} encerrará a solicitação e você receberá uma resposta de tempo limite como esta:
If {% data variables.product.prodname_dotcom %} takes more than 10 seconds to process an API request, {% data variables.product.prodname_dotcom %} will terminate the request and you will receive a timeout response like this:
```json
{
@ -330,23 +315,23 @@ Se {% data variables.product.prodname_dotcom %} leva mais de 10 segundos para pr
}
```
{% data variables.product.product_name %} se reserva o direito de alterar o período de tempo limite para proteger a velocidade e confiabilidade da API.
{% data variables.product.product_name %} reserves the right to change the timeout window to protect the speed and reliability of the API.
## Limitação de taxa
## Rate limiting
Os diferentes tipos de solicitações da API para {% data variables.location.product_location %} estão sujeitos a diferentes limites de taxa.
Different types of API requests to {% data variables.location.product_location %} are subject to different rate limits.
Além disso, a API de pesquisa tem limites dedicados. Para obter mais informações, confira "[Pesquisar](/rest/reference/search#rate-limit)" na documentação da API REST.
Additionally, the Search API has dedicated limits. For more information, see "[Search](/rest/reference/search#rate-limit)" in the REST API documentation.
{% data reusables.enterprise.rate_limit %}
{% data reusables.rest-api.always-check-your-limit %}
### Solicitações de contas pessoais
### Requests from personal accounts
As solicitações diretas da API que você autentica com um {% data variables.product.pat_generic %} são solicitações do usuário para servidor. Um aplicativo OAuth ou GitHub também pode fazer uma solicitação de usuário para servidor em seu nome depois de autorizar o aplicativo. Para obter mais informações, confira "[Como criar um {% data variables.product.pat_generic %}](/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token)", "[Como autorizar aplicativos OAuth](/authentication/keeping-your-account-and-data-secure/authorizing-oauth-apps)" e "[Como autorizar aplicativos GitHub](/authentication/keeping-your-account-and-data-secure/authorizing-github-apps)".
Direct API requests that you authenticate with a {% data variables.product.pat_generic %} are user-to-server requests. An OAuth App or GitHub App can also make a user-to-server request on your behalf after you authorize the app. For more information, see "[Creating a {% data variables.product.pat_generic %}](/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token)," "[Authorizing OAuth Apps](/authentication/keeping-your-account-and-data-secure/authorizing-oauth-apps)," and "[Authorizing GitHub Apps](/authentication/keeping-your-account-and-data-secure/authorizing-github-apps)."
{% data variables.product.product_name %} associa todas as solicitações de usuário para servidor ao usuário autenticado. Para aplicativos OAuth e aplicativos GitHub, este é o usuário que autorizou o aplicativo. Todos os pedidos de usuário-servidor contam para o limite de taxa do usuário autenticado.
{% data variables.product.product_name %} associates all user-to-server requests with the authenticated user. For OAuth Apps and GitHub Apps, this is the user who authorized the app. All user-to-server requests count toward the authenticated user's rate limit.
{% data reusables.apps.user-to-server-rate-limits %}
@ -356,33 +341,33 @@ As solicitações diretas da API que você autentica com um {% data variables.pr
{% ifversion fpt or ghec or ghes %}
Para solicitações não autenticadas, o limite de taxa permite até 60 solicitações por hora. As solicitações não autenticadas estão associadas ao endereço IP original, e não à pessoa que faz as solicitações.
For unauthenticated requests, the rate limit allows for up to 60 requests per hour. Unauthenticated requests are associated with the originating IP address, and not the person making requests.
{% endif %}
{% endif %}
### Solicitações de aplicativos GitHub
### Requests from GitHub Apps
As solicitações de um aplicativo GitHub podem ser de usuário para servidor ou de servidor para servidor. Para obter mais informações sobre limites de taxa para aplicativos GitHub, confira "[Limites de taxa para aplicativos GitHub](/developers/apps/building-github-apps/rate-limits-for-github-apps)".
Requests from a GitHub App may be either user-to-server or server-to-server requests. For more information about rate limits for GitHub Apps, see "[Rate limits for GitHub Apps](/developers/apps/building-github-apps/rate-limits-for-github-apps)."
### Solicitações do GitHub Actions
### Requests from GitHub Actions
Você pode utilizar o `GITHUB_TOKEN` integrado para autenticar as solicitações nos fluxos de trabalho do GitHub Actions. Para obter mais informações, confira "[Autenticação automática de token](/actions/security-guides/automatic-token-authentication)".
You can use the built-in `GITHUB_TOKEN` to authenticate requests in GitHub Actions workflows. For more information, see "[Automatic token authentication](/actions/security-guides/automatic-token-authentication)."
Quando `GITHUB_TOKEN` é usado, o limite de taxa é de 1.000 solicitações por hora por repositório.{% ifversion fpt or ghec %} Para solicitações a recursos que pertencem a uma conta corporativa na {% data variables.location.product_location %}, aplicam-se os limites de taxa do {% data variables.product.prodname_ghe_cloud %} e o limite é de 15.000 solicitações por hora por repositório.{% endif %}
When using `GITHUB_TOKEN`, the rate limit is 1,000 requests per hour per repository.{% ifversion fpt or ghec %} For requests to resources that belong to an enterprise account on {% data variables.location.product_location %}, {% data variables.product.prodname_ghe_cloud %}'s rate limit applies, and the limit is 15,000 requests per hour per repository.{% endif %}
### Verificando o status do seu limite da taxa
### Checking your rate limit status
A API de limite de taxa e os cabeçalhos HTTP de uma resposta são fontes autorizadas para o número atual de chamadas de API disponíveis para você ou seu aplicativo a qualquer momento.
The Rate Limit API and a response's HTTP headers are authoritative sources for the current number of API calls available to you or your app at any given time.
#### API de limite de taxa
#### Rate Limit API
Você pode usar a API do limite de taxa para verificar o status do seu limite de taxa sem impactar no limite atual. Para obter mais informações, confira "[Limite de taxa](/rest/reference/rate-limit)".
You can use the Rate Limit API to check your rate limit status without incurring a hit to the current limit. For more information, see "[Rate limit](/rest/reference/rate-limit)."
#### Cabeçalhos de HTTP de limite de taxa
#### Rate limit HTTP headers
Os cabeçalhos HTTP retornados de qualquer solicitação de API mostram o seu status atual de limite de taxa:
The returned HTTP headers of any API request show your current rate limit status:
```shell
$ curl -I {% data variables.product.api_url_pre %}/users/octocat
@ -394,21 +379,21 @@ $ curl -I {% data variables.product.api_url_pre %}/users/octocat
> x-ratelimit-reset: 1372700873
```
Nome do cabeçalho | Descrição
Header Name | Description
-----------|-----------|
`x-ratelimit-limit` | O número máximo de solicitações que você pode fazer por hora.
`x-ratelimit-remaining` | O número de solicitações restantes na janela de limite de taxa atual.
`x-ratelimit-used` | O número de solicitações feitas na janela de limite de taxa atual.
`x-ratelimit-reset` | O tempo em que a janela de limite de taxa atual é redefinida em [segundos de época UTC](http://en.wikipedia.org/wiki/Unix_time).
`x-ratelimit-limit` | The maximum number of requests you're permitted to make per hour.
`x-ratelimit-remaining` | The number of requests remaining in the current rate limit window.
`x-ratelimit-used` | The number of requests you've made in the current rate limit window.
`x-ratelimit-reset` | The time at which the current rate limit window resets in [UTC epoch seconds](http://en.wikipedia.org/wiki/Unix_time).
Se você precisar de outro formato de tempo, qualquer linguagem de programação moderna pode fazer o trabalho. Por exemplo, se você abrir o console em seu navegador, você pode facilmente obter o tempo de redefinição como um objeto de tempo do JavaScript.
If you need the time in a different format, any modern programming language can get the job done. For example, if you open up the console on your web browser, you can easily get the reset time as a JavaScript Date object.
``` javascript
new Date(1372700873 * 1000)
// => Mon Jul 01 2013 13:47:53 GMT-0400 (EDT)
```
Se você exceder o limite de taxa, uma resposta do erro retorna:
If you exceed the rate limit, an error response returns:
```shell
> HTTP/2 403
@ -424,9 +409,9 @@ Se você exceder o limite de taxa, uma resposta do erro retorna:
> }
```
### Aumentando o limite de taxa não autenticado para aplicativos OAuth
### Increasing the unauthenticated rate limit for OAuth Apps
Se o seu aplicativo OAuth precisar fazer chamadas não autenticadas com um limite de taxa mais alto, você poderá passar o ID e o segredo do cliente do seu aplicativo antes do encaminhamento de pontos de extremidade.
If your OAuth App needs to make unauthenticated calls with a higher rate limit, you can pass your app's client ID and secret before the endpoint route.
```shell
$ curl -u my_client_id:my_client_secret -I {% data variables.product.api_url_pre %}/user/repos
@ -440,21 +425,21 @@ $ curl -u my_client_id:my_client_secret -I {% data variables.product.api_url_pre
{% note %}
**Observação:** Nunca compartilhe seu segredo de cliente com alguém ou o inclua no código do navegador do lado do cliente. Use o método mostrado aqui apenas para chamadas de servidor para servidor.
**Note:** Never share your client secret with anyone or include it in client-side browser code. Use the method shown here only for server-to-server calls.
{% endnote %}
### Manter-se dentro do limite de taxa
### Staying within the rate limit
Se você exceder o limite de taxa usando a autenticação básica ou o OAuth, provavelmente poderá corrigir o problema armazenando em cache as respostas da API e usando [solicitações condicionais](#conditional-requests).
If you exceed your rate limit using Basic Authentication or OAuth, you can likely fix the issue by caching API responses and using [conditional requests](#conditional-requests).
### Limites de taxa secundária
### Secondary rate limits
A fim de fornecer serviço de qualidade no {% data variables.product.product_name %}, podem-se aplicar limites de taxa adicionais podem a algumas ações ao usar a API. Por exemplo, usar a API para criar rapidamente conteúdo, fazer sondagem de modo agressivo em vez de usar webhooks, fazer várias solicitações simultâneas ou solicitar repetidamente dados caros do ponto de vista computacional podem resultar na limitação da taxa secundária.
In order to provide quality service on {% data variables.product.product_name %}, additional rate limits may apply to some actions when using the API. For example, using the API to rapidly create content, poll aggressively instead of using webhooks, make multiple concurrent requests, or repeatedly request data that is computationally expensive may result in secondary rate limiting.
Limites de taxa secundária não pretendem interferir com o uso legítimo da API. Seus limites de taxa normais devem ser o único limite em que você deve focar. Para garantir que você esteja agindo como um bom cidadão da API, confira nossas [Diretrizes de Práticas Recomendadas](/guides/best-practices-for-integrators/).
Secondary rate limits are not intended to interfere with legitimate use of the API. Your normal rate limits should be the only limit you target. To ensure you're acting as a good API citizen, check out our [Best Practices guidelines](/guides/best-practices-for-integrators/).
Se seu aplicativo acionar este limite de taxa, você receberá uma resposta informativa:
If your application triggers this rate limit, you'll receive an informative response:
```shell
> HTTP/2 403
@ -469,18 +454,19 @@ Se seu aplicativo acionar este limite de taxa, você receberá uma resposta info
{% ifversion fpt or ghec %}
## Agente de usuário obrigatório
## User agent required
Todas as solicitações de API PRECISAM incluir um cabeçalho `User-Agent` válido. Solicitações sem cabeçalho `User-Agent` serão rejeitadas. Pedimos que use seu nome de usuário de {% data variables.product.product_name %} ou o nome de seu
aplicativo, para o valor do cabeçalho `User-Agent`. Isso nos permite entrar em contato com você, em caso de problemas.
All API requests MUST include a valid `User-Agent` header. Requests with no `User-Agent`
header will be rejected. We request that you use your {% data variables.product.product_name %} username, or the name of your
application, for the `User-Agent` header value. This allows us to contact you if there are problems.
Veja um exemplo:
Here's an example:
```shell
User-Agent: Awesome-Octocat-App
```
O cURL envia um cabeçalho `User-Agent` válido por padrão. Se você fornecer um cabeçalho `User-Agent` inválido via cURL (ou por meio de um cliente alternativo), receberá uma resposta `403 Forbidden`:
cURL sends a valid `User-Agent` header by default. If you provide an invalid `User-Agent` header via cURL (or via an alternative client), you will receive a `403 Forbidden` response:
```shell
$ curl -IH 'User-Agent: ' {% data variables.product.api_url_pre %}/meta
@ -495,15 +481,20 @@ $ curl -IH 'User-Agent: ' {% data variables.product.api_url_pre %}/meta
{% endif %}
## Solicitações condicionais
## Conditional requests
A maioria das respostas retorna um cabeçalho `ETag`. Muitas respostas também retornam um cabeçalho `Last-Modified`. Você pode usar os valores desses cabeçalhos para fazer solicitações subsequentes a esses recursos usando os cabeçalhos `If-None-Match` e `If-Modified-Since`, respectivamente. Se o recurso não tiver sido alterado, o servidor retornará um `304 Not Modified`.
Most responses return an `ETag` header. Many responses also return a `Last-Modified` header. You can use the values
of these headers to make subsequent requests to those resources using the
`If-None-Match` and `If-Modified-Since` headers, respectively. If the resource
has not changed, the server will return a `304 Not Modified`.
{% ifversion fpt or ghec %}
{% tip %}
**Observação**: Fazer uma solicitação condicional e receber uma resposta 304 não conta para o seu [Limite de Taxa](#rate-limiting). Portanto, recomendamos que você o utilize sempre que possível.
**Note**: Making a conditional request and receiving a 304 response does not
count against your [Rate Limit](#rate-limiting), so we encourage you to use it
whenever possible.
{% endtip %}
@ -540,12 +531,16 @@ $ curl -I {% data variables.product.api_url_pre %}/user -H "If-Modified-Since: T
> x-ratelimit-reset: 1372700873
```
## Compartilhamento de recursos entre origens
## Cross origin resource sharing
A API é compatível com Compartilhamento de Recursos de Origens Cruzadas (CORS) para solicitações de AJAX de qualquer origem.
Você pode ler a [Recomendação CORS W3C](http://www.w3.org/TR/cors/) ou [esta introdução](https://code.google.com/archive/p/html5security/wikis/CrossOriginRequestSecurity.wiki) do Guia de Segurança HTML 5.
The API supports Cross Origin Resource Sharing (CORS) for AJAX requests from
any origin.
You can read the [CORS W3C Recommendation](http://www.w3.org/TR/cors/), or
[this intro](https://code.google.com/archive/p/html5security/wikis/CrossOriginRequestSecurity.wiki) from the
HTML 5 Security Guide.
Aqui está uma solicitação de exemplo enviada de um navegador atingindo `http://example.com`:
Here's a sample request sent from a browser hitting
`http://example.com`:
```shell
$ curl -I {% data variables.product.api_url_pre %} -H "Origin: http://example.com"
@ -554,7 +549,7 @@ Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, x-ratelimit-limit, x-ratelimit-remaining, x-ratelimit-reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
```
A solicitação pré-voo de CORS se parece com isso:
This is what the CORS preflight request looks like:
```shell
$ curl -I {% data variables.product.api_url_pre %} -H "Origin: http://example.com" -X OPTIONS
@ -566,9 +561,13 @@ Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, x-ratelimit-limit, x-ra
Access-Control-Max-Age: 86400
```
## Chamadas de retorno do JSON-P
## JSON-P callbacks
Você pode enviar um parâmetro `?callback` para qualquer chamada de GET para envolver os resultados em uma função JSON. Isso geralmente é usado quando os navegadores desejam incorporar o conteúdo do {% data variables.product.product_name %} em páginas da Web, contornando problemas entre domínios. A resposta inclui a mesma saída de dados da API regular, mais as informações relevantes do cabeçalho de HTTP.
You can send a `?callback` parameter to any GET call to have the results
wrapped in a JSON function. This is typically used when browsers want
to embed {% data variables.product.product_name %} content in web pages by getting around cross domain
issues. The response includes the same data output as the regular API,
plus the relevant HTTP Header information.
```shell
$ curl {% data variables.product.api_url_pre %}?callback=foo
@ -589,7 +588,7 @@ $ curl {% data variables.product.api_url_pre %}?callback=foo
> })
```
Você pode escrever um manipulador do JavaScript para processar o retorno de chamada. Aqui está um exemplo pequeno que você pode experimentar:
You can write a JavaScript handler to process the callback. Here's a minimal example you can try out:
<html>
<head>
@ -613,13 +612,15 @@ Você pode escrever um manipulador do JavaScript para processar o retorno de cha
</body>
</html>
Todos os cabeçalhos têm o mesmo valor da string que os cabeçalhos de HTTP com uma exceção notável: Link. Cabeçalhos de link são pré-analisados para você e chegam como um array de tuplas de `[url, options]`.
All of the headers are the same String value as the HTTP Headers with one
notable exception: Link. Link headers are pre-parsed for you and come
through as an array of `[url, options]` tuples.
Um link que se parece com isto:
A link that looks like this:
Link: <url1>; rel="next", <url2>; rel="foo"; bar="baz"
... será mostrado assim na saída da chamada de retorno:
... will look like this in the Callback output:
```json
{
@ -641,39 +642,37 @@ Um link que se parece com isto:
}
```
## Fusos horários
## Timezones
Algumas solicitações que criam novos dados, como a criação de um novo commit, permitem que você forneça informações do fuso horário ao especificar ou marcas de tempo. Aplicamos as seguintes regras, por ordem de prioridade, para determinar as informações do fuso horário para essas chamadas da API.
Some requests that create new data, such as creating a new commit, allow you to provide time zone information when specifying or generating timestamps. We apply the following rules, in order of priority, to determine timezone information for such API calls.
* [Fornecer explicitamente uma marca de tempo ISO 8601 com informações de fuso horário](#explicitly-providing-an-iso-8601-timestamp-with-timezone-information)
* [Usar o cabeçalho `Time-Zone`](#using-the-time-zone-header)
* [Usar o último fuso horário conhecido para o usuário](#using-the-last-known-timezone-for-the-user)
* [Definir como padrão UTC sem outras informações de fuso horário](#defaulting-to-utc-without-other-timezone-information)
* [Explicitly providing an ISO 8601 timestamp with timezone information](#explicitly-providing-an-iso-8601-timestamp-with-timezone-information)
* [Using the `Time-Zone` header](#using-the-time-zone-header)
* [Using the last known timezone for the user](#using-the-last-known-timezone-for-the-user)
* [Defaulting to UTC without other timezone information](#defaulting-to-utc-without-other-timezone-information)
Observe que essas regras se aplicam somente a dados passados para a API, não a dados retornados pela API. Conforme mencionado no "[Esquema](#schema)", os registros de hora retornados pela API estão em formato UTC, ISO 8601.
Note that these rules apply only to data passed to the API, not to data returned by the API. As mentioned in "[Schema](#schema)," timestamps returned by the API are in UTC time, ISO 8601 format.
### Fornecer explicitamente uma marca de tempo ISO 8601 com informações de fuso horário
### Explicitly providing an ISO 8601 timestamp with timezone information
Para chamadas de API que permitem que uma marca de tempo seja especificada, usamos essa marca de tempo exata. Um exemplo disso é a [API Commits](/rest/reference/git#commits).
For API calls that allow for a timestamp to be specified, we use that exact timestamp. An example of this is the [Commits API](/rest/reference/git#commits).
Esses carimbos de data/hora se parecem com `2014-02-27T15:05:06+01:00`. Confira também [este exemplo](/rest/reference/git#example-input) para saber como esses carimbos de data/hora podem ser especificados.
These timestamps look something like `2014-02-27T15:05:06+01:00`. Also see [this example](/rest/reference/git#example-input) for how these timestamps can be specified.
### Usar o cabeçalho `Time-Zone`
### Using the `Time-Zone` header
É possível fornecer um cabeçalho `Time-Zone` que define um fuso horário de acordo com a [lista de nomes do banco de dados Olson](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
It is possible to supply a `Time-Zone` header which defines a timezone according to the [list of names from the Olson database](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
```shell
$ curl -H "Time-Zone: Europe/Amsterdam" -X POST {% data variables.product.api_url_pre %}/repos/github/linguist/contents/new_file.md
```
Isso significa que geramos uma marca de tempo no momento em que sua chamada de API é feita no fuso horário que este cabeçalho define. Por exemplo, o [API de Conteúdo](/rest/reference/repos#contents) gera um commit do git para cada adição ou alteração e usa a hora atual como marca de tempo. Este cabeçalho determinará o fuso horário usado para gerar essa marca de tempo atual.
This means that we generate a timestamp for the moment your API call is made in the timezone this header defines. For example, the [Contents API](/rest/reference/repos#contents) generates a git commit for each addition or change and uses the current time as the timestamp. This header will determine the timezone used for generating that current timestamp.
### Usar o último fuso horário conhecido para o usuário
### Using the last known timezone for the user
Se nenhum cabeçalho `Time-Zone` for especificado e você fizer uma chamada autenticada para a API, nós usaremos o último fuso horário conhecido para o usuário autenticado. O último fuso horário conhecido é atualizado sempre que você navegar no site de {% data variables.product.product_name %}.
If no `Time-Zone` header is specified and you make an authenticated call to the API, we use the last known timezone for the authenticated user. The last known timezone is updated whenever you browse the {% data variables.product.product_name %} website.
### Definir como padrão UTC sem outras informações de fuso horário
### Defaulting to UTC without other timezone information
Se as etapas acima não resultarem em nenhuma informação, usaremos UTC como o fuso horário para criar o commit do git.
[pagination-guide]: /guides/traversing-with-pagination
If the steps above don't result in any information, we use UTC as the timezone to create the git commit.

Просмотреть файл

@ -1,13 +0,0 @@
{% ifversion not fpt or ghec %}
{% note %}
**Note**: The following guide uses the REST API for {% data variables.product.prodname_dotcom_the_website %}.
- Use <code>{% data variables.product.api_url_pre %}</code> to access the API for {% data variables.product.product_name %}.
- The guide specifies usernames and repositories that may not exist on {% data variables.location.product_location %}. You may need to use different names to see similar output.
{% endnote %}
{% endif %}