Our payments API is documented at the developer portal.
Nossa API de pagamentos está documentada no portal do desenvolvedor.Aula
APIs e contratos em inglês
Nível: B1
Objetivo
Discutir APIs, contratos e mudanças em inglês, descrevendo endpoints, payloads, headers, schemas, autenticação, autorização, rate limit e compatibilidade básica com consumidores.
Explicação
Uma API (Application Programming Interface) é o contrato entre serviços: define como um cliente pede dados e como o servidor responde. Em uma API REST, cada endpoint (URL como `/orders` ou `/users/42`) representa um recurso.
Uma chamada HTTP é composta por:
- Request (requisição): o método (`GET`, `POST`, `PUT`, `DELETE`), o endpoint, os headers (metadados como token de autenticação e tipo de conteúdo) e, em alguns métodos, um payload (corpo da requisição, geralmente em JSON).
- Response (resposta): um status code (por exemplo `200 OK`, `400 Bad Request`, `401 Unauthorized`, `429 Too Many Requests`, `500 Internal Server Error`) e um payload de resposta.
Authentication confirma quem é o chamador (por exemplo, um token JWT, uma API key). Authorization decide o que esse chamador pode fazer (permissões, escopos). As duas vêm juntas: primeiro autentica, depois autoriza.
O schema descreve a forma dos dados: nomes de campos, tipos e obrigatoriedade. É o que permite ao cliente validar a resposta e gerar código automaticamente.
Rate limit limita quantas chamadas um cliente pode fazer em um intervalo (por exemplo, 1000 requisições por hora). Quando o limite é excedido, a API devolve `429 Too Many Requests`.
Mudanças e compatibilidade
- Non-breaking change (mudança sem quebra): adicionar um campo opcional na resposta, incluir um novo endpoint, ampliar o rate limit. Consumidores antigos continuam funcionando.
- Breaking change (mudança com quebra): renomear ou remover um campo, mudar o tipo de um campo, exigir autenticação onde não exigia, estreitar o rate limit sem aviso. Consumidores antigos quebram.
Para discutir mudanças, use padrões como:
- `We're deprecating the v1 endpoint. It will be removed on March 1st.`
- `The new field is optional, so it's a non-breaking change.`
- `We need to update the schema to require a new header.`
- `Let's check who depends on this field before we remove it.`
Versioning (versionamento) ajuda: manter `v1` e `v2` lado a lado dá tempo para os consumers migrarem. Deprecate significa marcar algo como obsoleto, dando aviso prévio antes de remover.
Exemplos
| Inglês | Tradução | Observação |
|---|---|---|
| Could you check the response payload for the new endpoint? | Você poderia verificar o payload de resposta do novo endpoint? | Pedido para inspecionar o corpo da resposta. |
| We added an Authorization header to the request. | Adicionamos um header Authorization à requisição. | Header transporta credenciais. |
| This is a breaking change because we removed the `legacy_id` field. | Esta é uma mudança com quebra porque removemos o campo `legacy_id`. | Remover campo quebra consumidores. |
| The new field is optional, so existing clients won't break. | O novo campo é opcional, então clientes existentes não quebram. | Campo opcional = non-breaking. |
| We hit the rate limit at 11:30 and got a 429. | Batemos o rate limit às 11h30 e recebemos um 429. | 429 Too Many Requests. |
| We'll deprecate the v1 schema in two months. | Vamos descontinuar o schema v1 em dois meses. | Deprecate = marcar como obsoleto. |
| Authentication failed: the API key in the header is invalid. | Falha de autenticação: a API key no header é inválida. | Authentication verifica identidade. |
| The token is valid, but the user doesn't have authorization to delete the resource. | O token é válido, mas o usuário não tem autorização para deletar o recurso. | Authorization verifica permissões. |
Erros comuns
- Trocar authentication e authorization: authentication pergunta `who are you?`, authorization pergunta `what can you do?`.
- Confundir endpoint com URL completa: o endpoint é o caminho (`/orders`); a URL inclui o host (`https://api.example.com/orders`).
- Dizer `we breaked` ou `breaked the contract`: o correto é `we broke` ou `we introduced a breaking change`.
- Dizer `the API is deprecating` quando o que se descontinua é o endpoint ou o campo, não a API inteira: prefira `we're deprecating this endpoint`.
- Esquecer que o payload pode estar no request ou no response: especifique `request payload` ou `response payload` quando houver ambiguidade.
- Traduzir `consumidor` literalmente como `consumer` em contextos informais: em inglês técnico, `consumer` (o cliente da API) é a forma padrão.
Prática guiada
Releia este pequeno cenário e responda em voz alta em inglês:
> A equipe de pagamentos está prestes a remover o campo `legacy_id` da resposta do endpoint `/transactions`. Eles também vão exigir um header `X-Api-Key` em todas as chamadas.
- Essa mudança é breaking? Por quê? Resposta-modelo: `Yes, it's a breaking change. Removing a field breaks clients that read it, and requiring a new header breaks clients that don't send it.`
- Como comunicar isso aos consumidores? Resposta-modelo: `We should deprecate the old behavior first, document the change in the changelog, and give clients at least one release cycle to migrate.`
- Que tipo de erro o cliente antigo vai receber? Resposta-modelo: `Clients without the new header will get a 401 Unauthorized, and clients reading the removed field will get missing data or a 500.`
Resumo
Endpoints expõem recursos; requests enviam método, headers e payload opcional; responses voltam com status code e payload. Authentication valida identidade, authorization valida permissões, schema descreve o formato e rate limit controla volume. Mudanças breaking quebram consumidores; mudanças non-breaking são seguras. Deprecate, versioning e changelog dão tempo de migrar.
Vocabulário
Palavras principais
The /orders endpoint returns a list of orders.
O endpoint /orders retorna uma lista de pedidos.The request payload must be valid JSON.
O payload da requisição deve ser JSON válido.Set the Content-Type header to application/json.
Defina o header Content-Type como application/json.The request includes a bearer token in the Authorization header.
A requisição inclui um bearer token no header Authorization.The response returns a 200 status code and a JSON body.
A resposta retorna status 200 e um corpo em JSON.A 404 status code means the resource was not found.
Um status code 404 significa que o recurso não foi encontrado.Authentication failed because the token expired.
A autenticação falhou porque o token expirou.The user passed authentication but failed authorization for that resource.
O usuário passou na autenticação mas falhou na autorização para aquele recurso.Send your API key in the X-Api-Key header.
Envie sua API key no header X-Api-Key.We updated the schema to make the email field required.
Atualizamos o schema para tornar o campo email obrigatório.We hit the rate limit after 1000 requests per hour.
Batemos o rate limit após 1000 requisições por hora.We need to notify all consumers before we remove the field.
Precisamos avisar todos os consumidores antes de remover o campo.Renaming a field is a breaking change.
Renomear um campo é uma breaking change.Adding an optional field is a non-breaking change.
Adicionar um campo opcional é uma non-breaking change.We deprecate the old endpoint in favor of the new one.
Descontinuamos o endpoint antigo em favor do novo.'We use URL versioning: /v1/orders and /v2/orders.'
'Usamos versionamento por URL: /v1/orders e /v2/orders.'Always read the changelog before upgrading.
Sempre leia o changelog antes de atualizar.História
História: APIs e contratos em inglês
Nível: B1
História em inglês
Planning the v2 release
On Monday morning, Lena, a backend engineer, opened a meeting to discuss the v2 of the payments API. "The current endpoint /payments returns a lot of fields our consumers don't actually use," she said. "We want to clean up the schema, but we cannot break existing clients." Her colleague Bruno suggested removing the `legacy_id` field from the response payload. Lena replied, "That would be a breaking change. Some clients still read that field." They decided to keep the field but mark it as deprecated in the documentation.
Tightening security
Next, Bruno raised the authentication and authorization policy. "Right now, anyone with a valid API key can call the /refund endpoint," he said. "Authentication passes, but authorization should require the new `refunds:write` scope." Lena agreed, but she warned, "This is also a breaking change for clients that don't request that scope yet." They planned to roll it out in two steps: first add the scope check, then enforce it.
Rate limits and the changelog
Tomas, the platform lead, joined the call and asked about rate limits. "We're seeing some consumers hit the rate limit during peak hours and getting 429s," he explained. Lena proposed raising the rate limit from 1000 to 2000 requests per hour. "That's a non-breaking change," Bruno confirmed. "It only affects the headers, not the payload." Tomas asked for a clear changelog entry, with examples of the new request payload and the new status codes. By the end of the meeting, the team agreed: deprecate the legacy field, add the scope check, raise the rate limit, and document everything.
Tradução linha por linha
| Inglês | Tradução |
|---|---|
| On Monday morning, Lena, a backend engineer, opened a meeting to discuss the v2 of the payments API. | Na segunda de manhã, Lena, engenheira de backend, abriu uma reunião para discutir a v2 da API de pagamentos. |
| "The current endpoint /payments returns a lot of fields our consumers don't actually use," she said. | “O endpoint atual /payments retorna muitos campos que nossos consumidores na verdade não usam”, disse ela. |
| "We want to clean up the schema, but we cannot break existing clients." | “Queremos limpar o schema, mas não podemos quebrar clientes existentes.” |
| Her colleague Bruno suggested removing the `legacy_id` field from the response payload. | O colega Bruno sugeriu remover o campo `legacy_id` do payload de resposta. |
| Lena replied, "That would be a breaking change. Some clients still read that field." | Lena respondeu: “Isso seria uma breaking change. Alguns clientes ainda leem esse campo.” |
| They decided to keep the field but mark it as deprecated in the documentation. | Decidiram manter o campo, mas marcá-lo como descontinuado na documentação. |
| Next, Bruno raised the authentication and authorization policy. | Em seguida, Bruno levantou a política de autenticação e autorização. |
| "Right now, anyone with a valid API key can call the /refund endpoint," he said. | “Hoje, qualquer pessoa com uma API key válida pode chamar o endpoint /refund”, disse ele. |
| "Authentication passes, but authorization should require the new `refunds:write` scope." | “A autenticação passa, mas a autorização deveria exigir o novo escopo `refunds:write`.” |
| Lena agreed, but she warned, "This is also a breaking change for clients that don't request that scope yet." | Lena concordou, mas avisou: “Isso também é uma breaking change para clientes que ainda não pedem esse escopo.” |
| They planned to roll it out in two steps: first add the scope check, then enforce it. | Planejaram lançar em duas etapas: primeiro adicionar a checagem de escopo e depois aplicá-la. |
| Tomas, the platform lead, joined the call and asked about rate limits. | Tomas, líder de plataforma, entrou na chamada e perguntou sobre rate limits. |
| "We're seeing some consumers hit the rate limit during peak hours and getting 429s," he explained. | “Estamos vendo alguns consumidores baterem o rate limit em horário de pico e recebendo 429s”, explicou. |
| Lena proposed raising the rate limit from 1000 to 2000 requests per hour. | Lena propôs aumentar o rate limit de 1000 para 2000 requisições por hora. |
| "That's a non-breaking change," Bruno confirmed. "It only affects the headers, not the payload." | “Isso é uma non-breaking change”, confirmou Bruno. “Afeta apenas os headers, não o payload.” |
| Tomas asked for a clear changelog entry, with examples of the new request payload and the new status codes. | Tomas pediu uma entrada clara no changelog, com exemplos do novo payload de requisição e dos novos status codes. |
| By the end of the meeting, the team agreed: deprecate the legacy field, add the scope check, raise the rate limit, and document everything. | Ao final da reunião, a equipe concordou: descontinuar o campo legados, adicionar a checagem de escopo, aumentar o rate limit e documentar tudo. |
Notas de vocabulário
- endpoint = caminho que identifica o recurso, como /payments ou /refund
- schema = definição da estrutura dos dados retornados pela API
- breaking change = mudança incompatível com versões anteriores, quebra consumidores
- deprecate = marcar como obsoleto com prazo, sem remover de imediato
- authentication = verifica a identidade do chamador (token, API key)
- authorization = verifica permissões, geralmente por escopo ou papel
- scope = permissão específica, como `refunds:write`, exigida pela autorização
- rate limit = número máximo de chamadas permitidas em um intervalo
- 429 = status code Too Many Requests, retornado quando o rate limit é excedido
- non-breaking change = mudança compatível com versões anteriores
- changelog = registro público das mudanças feitas em cada versão da API
- payload = corpo da requisição ou resposta, geralmente em JSON
Perguntas de compreensão
- Which endpoint did Bruno suggest cleaning up?
- Why is removing the `legacy_id` field a breaking change?
- What did the team decide to do with the `legacy_id` field for now?
- Which new scope does the team want to require for refunds?
- Why is adding the scope check also a breaking change?
- What status code were some consumers getting when they hit the rate limit?
- What change to the rate limit did Lena propose?
- Why did Bruno say the rate limit change is non-breaking?
- What did Tomas ask for in the changelog?
- List the four actions the team agreed on by the end of the meeting.
Prática com a história
- Reescreva em pergunta: We need to require the new scope for refunds.
- Traduza: Vamos aumentar o rate limit para 2000 requisições por hora.
- Corrija: We are deprecating the API on March 1st.
- Classifique como breaking ou non-breaking: adicionar a checagem do escopo refunds:write.
- Reescreva em negativa: The team removed the legacy field.
Prática
Exercícios e teste
A próxima melhoria é transformar esses arquivos em perguntas com resposta no navegador. Por enquanto, esta página já organiza o estudo e permite seguir a aula inteira sem abrir os arquivos manualmente.