Documentação da API NFS-eNFS-e API Documentation
Emita, consulte e cancele Notas Fiscais de Serviço Eletrônicas via API REST. Ambientes Sandbox e Produção, autenticação Bearer, e um console de testes embutido em cada endpoint. Issue, look up and cancel electronic service invoices (NFS-e) through a REST API. Sandbox and Production environments, Bearer authentication, and a built-in test console on every endpoint.
entidadeCity identification: entidade header
Comece por aquiGet started
Ambientes, headers obrigatórios e como gerar seu primeiro token.Environments, required headers, and how to generate your first token.
Referência da APIAPI Reference
Endpoints, parâmetros e exemplos de código em cURL, PHP, Node.js e Python.Endpoints, parameters, and ready-to-copy code samples in cURL, PHP, Node.js and Python.
Status da APIAPI Status
Verifique em tempo real se o ambiente Sandbox está respondendo.Check in real time whether the Sandbox environment is responding.
QuickstartQuickstart
Fluxo completo para emitir sua primeira NFS-e de teste no Sandbox, do zero, em 4 passos. The complete flow to issue your first test invoice on the Sandbox, from scratch, in 4 steps.
entidade?First things first: what is the entidade?É o slug que identifica o município (prefeitura/cliente) que você está integrando. Cada um tem o seu próprio, fornecido pela equipe responsável pela implantação. Ele é obrigatório em toda chamada da API, inclusive na geração do token; sem ele, nem essa parte funciona. It's the slug identifying the municipality (city hall/client) you're integrating with. Each one has its own, provided by whoever set up the integration. It's required on every API call, including token generation; without it, not even that step works.
Clique em Autorizar no topo da página e informe a sua uma única vez. O valor fica salvo nesta aba do navegador e é reaproveitado automaticamente em todos os passos e painéis de teste abaixo. Click Authorize at the top of the page and enter yours once. It's saved in this browser tab and automatically reused across every step and test panel below.
Autorizar & gerar tokenAuthorize & get a token
Gere um token Bearer com o cpf_cnpj, email e password de um usuário do Sandbox. Ele vale por 12h.
Generate a Bearer token with the cpf_cnpj, email and password of a Sandbox user. It's valid for 12h.
Cadastrar o tomadorRegister the customer
Toda NFS-e exige um tomador já cadastrado. Envie ao menos razao_social, endereco e o documento (cpf_cnpj ou nif).
Every invoice requires an already-registered customer. Send at least razao_social, endereco and the document (cpf_cnpj or nif).
Emitir a NFS-eIssue the invoice
Com o token e o tomador prontos, envie os dados do serviço, a localização (códigos IBGE) e os valores. A resposta traz a chave da nota.
With the token and customer ready, send the service data, location (IBGE codes) and amounts. The response returns the invoice's chave.
Cancelar (opcional)Cancel (optional)
Para desfazer uma emissão de teste, cancele usando a chave retornada no passo anterior e um motivo.
To undo a test issuance, cancel it using the chave returned in the previous step and a reason.
1Visão geralOverview
A API opera em dois ambientes independentes, selecionados diretamente pelo caminho da rota.The API runs on two independent environments, selected directly through the route path.
2Segurança & boas práticasSecurity & best practices
Recomendações baseadas no comportamento real dos middlewares de autenticação.Recommendations based on the real behavior of the authentication middlewares.
| PráticaPractice | MotivoReason |
|---|---|
| Nunca reutilize credenciais de produção em Sandbox (ou vice-versa)Never reuse Production credentials in Sandbox (or vice-versa) | Tokens são segregados por ambiente (ambiente = 1 produção / 2 sandbox); um token de Sandbox não autentica em Produção.Tokens are segregated per environment (ambiente = 1 production / 2 sandbox); a Sandbox token will not authenticate in Production. |
| Armazene o token com o mesmo cuidado de uma senhaStore the token with the same care as a password | O token é um Bearer de 80 caracteres, válido por 12h; qualquer portador da string é autenticado como o contribuinte.The token is an 80-character Bearer, valid for 12h; anyone holding the string is authenticated as that taxpayer. |
Sempre trate codigo (corpo) e HTTP status juntosAlways handle codigo (body) and the HTTP status together |
O campo codigo não segue 1:1 o HTTP status. Por exemplo, codigo 201 ocorre com HTTP 401. Veja Códigos de retorno.The codigo field does not map 1:1 to the HTTP status. For example, codigo 201 occurs with HTTP 401. See Response codes. |
Reautentique a cada 12h ou trate codigo 202Re-authenticate every 12h or handle codigo 202 |
Uma nova chamada de /auth/token renova o token do mesmo usuário/ambiente automaticamente.A new call to /auth/token automatically renews the token for the same user/environment. |
| Cadastre o tomador antes de emitir a NFS-eRegister the customer before issuing the invoice | O emissor resolve documento_tomador contra a base de tomadores do contribuinte; se não existir, a emissão falha com erro de validação.The issuer resolves documento_tomador against the taxpayer's customer records; if it doesn't exist, issuance fails with a validation error. |
| Use HTTPS em produçãoUse HTTPS in production | O header Authorization trafega o token em texto plano; sem TLS ele fica exposto na rede.The Authorization header carries the token in plain text; without TLS it is exposed on the network. |
localStorage). Ele é descartado ao recarregar a página.
This page's test panel is deliberately restricted to the Sandbox environment and keeps the token only in browser memory (never in localStorage). It is discarded on page reload.
3Ambientes e rotasEnvironments & routes
Cada operação possui uma rota equivalente em Sandbox e em Produção.Each operation has an equivalent route in Sandbox and Production.
| MétodoMethod | Sandbox | ProduçãoProduction | FinalidadePurpose |
|---|---|---|---|
| POST | /api/v1/sandbox/auth/token | /api/v1/production/auth/token | Gerar/renovar tokenGenerate/renew token |
| POST | /api/v1/sandbox/tomadores | /api/v1/production/tomadores | Cadastrar/processar tomadorCreate/process customer |
| GET | /api/v1/sandbox/tomadores | /api/v1/production/tomadores | Consultar tomadoresList customers |
| POST | /api/v1/sandbox/nfse | /api/v1/production/nfse | Cadastrar/processar NFS-eCreate/process invoice |
| POST | /api/v1/sandbox/nfse/{chave}/cancelar | /api/v1/production/nfse/{chave}/cancelar | Cancelar NFS-eCancel invoice |
/api/v1/.... Exemplo local já usado: /keep/nfs-e/api/v1/sandbox/...
If the application lives in a subdirectory, the project's physical path comes before /api/v1/.... Local example already in use: /keep/nfs-e/api/v1/sandbox/...
4Headers e autenticaçãoHeaders & authentication
| Header | ObrigatórioRequired | Valor / formatoValue / format | ObservaçãoNote |
|---|---|---|---|
| entidade | string (slug) | Enviado em todas as requisições, inclusive autenticação. Ausência ou slug inexistente retorna codigo 203 (HTTP 422).Sent on every request, including authentication. Missing or unknown slug returns codigo 203 (HTTP 422). | |
| Authorization | Sim*Yes* | Bearer {token} | *Exceto na geração do token.*Except when generating the token. |
| Content-Type | Sim para POSTYes for POST | application/json | Corpo em JSON.JSON body. |
| Accept | RecomendadoRecommended | application/json | Resposta em JSON.JSON response. |
5Limites de requisiçõesRate limits
Todos os endpoints da API são limitados por IP de origem, com um limite adicional na geração de token. All API endpoints are rate-limited by source IP, with an additional limit on token generation.
| EscopoScope | LimiteLimit | BaseBasis |
|---|---|---|
Todos os endpoints /api/v1/*All /api/v1/* endpoints |
60 requisições/minutorequests/minute | Por IP de origemPer source IP |
POST /auth/token (adicional)(additional) |
5 requisições/minutorequests/minute | Por IP de origemPer source IP |
/auth/token é somado ao limite geral: nessa rota, o que esgotar primeiro (5/min ou 60/min) bloqueia a chamada.
The /auth/token limit stacks with the general one: on that route, whichever runs out first (5/min or 60/min) blocks the call.
{
"message": "Too Many Attempts."
}
A resposta também inclui os headers Retry-After, X-RateLimit-Limit e X-RateLimit-Remaining.
The response also includes the Retry-After, X-RateLimit-Limit and X-RateLimit-Remaining headers.
6GlossárioGlossary
Termos do domínio fiscal/NFS-e usados ao longo desta documentação. Tax/NFS-e domain terms used throughout this documentation.
| TermoTerm | DefiniçãoDefinition |
|---|---|
| NFS-e | Nota Fiscal de Serviço Eletrônica: documento fiscal eletrônico emitido por prestadores de serviço no âmbito municipal.Electronic Service Invoice: the electronic tax document issued by service providers at the municipal level. |
| DPS | Declaração de Prestação de Serviços: declaração enviada para gerar a NFS-e dentro do padrão nacional (Ambiente de Dados Nacional).Service Provision Declaration: the declaration submitted to generate the NFS-e under the national standard (National Data Environment). |
| RPS | Recibo Provisório de Serviços: documento provisório emitido antes da NFS-e definitiva, posteriormente substituído por ela.Provisional Service Receipt: a provisional document issued before the definitive NFS-e, later replaced by it. |
| NBS | Nomenclatura Brasileira de Serviços: código nacional de classificação de serviços, intangíveis e outras operações.Brazilian Services Nomenclature: the national classification code for services, intangibles and other operations. |
| Item de serviçoService item | Código da lista de serviços (LC 116/2003). A variante nacional segue a tabela federal; a municipal é o refinamento local, quando existente.Service list code (Federal Law 116/2003). The national variant follows the federal table; the municipal one is the local refinement, when it exists. |
| Código IBGEIBGE code | Identificador numérico de 7 dígitos atribuído pelo IBGE a cada município brasileiro.The 7-digit numeric identifier assigned by IBGE to each Brazilian municipality. |
| ISS | Imposto sobre Serviços: tributo municipal incidente sobre a prestação de serviços.Service Tax: the municipal tax levied on the provision of services. |
| TomadorCustomer | Pessoa física ou jurídica que contrata e paga pelo serviço prestado: o cliente da nota.The individual or company that hires and pays for the service: the invoice's customer. |
| ContribuinteTaxpayer | Prestador do serviço, autenticado na API e responsável pela emissão da NFS-e.The service provider, authenticated in the API and responsible for issuing the invoice. |
| CompetênciaReference month | Mês de referência (formato YYYY-MM) ao qual a obrigação fiscal da nota se refere.The reference month (YYYY-MM format) the invoice's tax obligation refers to. |
| DAM | Documento de Arrecadação Municipal: guia de pagamento municipal. Uma NFS-e vinculada a um DAM pago ou em cobrança não pode ser cancelada livremente.Municipal Tax Collection Document: a municipal payment slip. An invoice linked to a paid or in-collection DAM cannot be freely cancelled. |
| Ambiente Nacional (ADN)National Environment (ADN) | Ambiente de Dados Nacional: infraestrutura federal que recebe e valida as NFS-e em produção.National Data Environment: the federal infrastructure that receives and validates invoices in production. |
| Chave de acessoAccess key | Identificador único gerado na emissão, usado para consultar ou cancelar a NFS-e (campo chave).The unique identifier generated at issuance, used to look up or cancel the invoice (chave field). |
| Código de verificaçãoVerification code | Código retornado na emissão para verificação pública de autenticidade da nota.The code returned at issuance for public authenticity verification of the invoice. |
7Gerar tokenGet token
Endpoint:Endpoint: POST /api/v1/{ambiente}/auth/token. Exemplos e teste ao vivo no painel à direita →Examples and live test in the right-hand panel →
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| cpf_cnpj | string | CPF/CNPJ do contribuinte (deve possuir emite_nota = 1 e item de serviço configurado).Taxpayer's CPF/CNPJ (must have emite_nota = 1 and a configured service item). | |
| e-mail válidovalid e-mail | E-mail do usuário vinculado ao contribuinte.E-mail of the user linked to the taxpayer. | ||
| password | string | Senha do usuário.User's password. |
expires_in: 43200). Uma nova autenticação do mesmo usuário e ambiente renova (substitui) o token existente. Não empilha tokens.
The token is valid for 12 hours (expires_in: 43200). A new authentication for the same user and environment renews (replaces) the existing token. Tokens are not stacked.
{
"codigo": 200,
"descricao": "Autenticação realizada com sucesso.",
"token": "aQ7f...(80 caracteres)",
"token_type": "Bearer",
"expires_in": 43200,
"expira_em": "2026-09-29 04:10:51"
}
{
"codigo": 401,
"descricao": "CNPJ, e-mail ou senha inválidos."
}
8Cadastro de tomadorCustomer registration
Endpoint:Endpoint: POST /api/v1/{ambiente}/tomadores. RequerRequires Authorization: Bearer {token}
cpf_cnpj ou nif para o contribuinte autenticado, a API não cria duplicado: retorna o tomador existente com codigo 204 (HTTP continua 200).
If a customer with the same cpf_cnpj or nif already exists for the authenticated taxpayer, the API does not create a duplicate: it returns the existing customer with codigo 204 (HTTP remains 200).
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| razao_social | string, máx. 100 | Razão social / nome.Legal name. | |
| fantasia | string, máx. 100 | Nome fantasia.Trade name. | |
| cpf_cnpj | string, máx. 18 | CPF ou CNPJ (validado por dígito verificador). Para brasileiro, o tipo (física/jurídica) é inferido pelo tamanho após normalização (11 = CPF, 14 = CNPJ).CPF or CNPJ (validated by check digit). For a Brazilian party, the type (individual/company) is inferred from the length after normalization (11 = CPF, 14 = CNPJ). | |
| nif | string, máx. 40 | NIF do estrangeiro.Foreign taxpayer's NIF. | |
| nao_nif | integer | Indicador de ausência de NIF.Flag indicating the absence of a NIF. | |
| e-mail, máx. 100 | E-mail.E-mail. | ||
| contato | string, máx. 20 | Contato principal.Primary contact. | |
| contato2 | string, máx. 20 | Contato secundário.Secondary contact. | |
| pais | Não*No* | string, máx. 100 | Nome do país (ex.: Brasil). Se omitido, assume Brasil (id 31).Country name (e.g. Brasil). Defaults to Brazil (id 31) if omitted. |
| estado | Não (ignorado)No (ignored) |
O campo estado pode ser enviado, mas não é utilizado pela API atualmente.
The estado field can be sent, but is not currently used by the API.
|
|
| cidade | Condicional (Brasil)Conditional (Brazil) | string/integer |
Obrigatória para tomador no Brasil. O valor esperado é o código IBGE do município (ex.: 2927408), não o nome da cidade como texto.
Required for a Brazilian customer. The expected value is the IBGE municipality code (e.g. 2927408), not the city name as free text.
|
| cep | string, máx. 11 | CEP/código postal.Postal code. | |
| endereco | string, máx. 100 | Endereço.Address. | |
| numero | string, máx. 10 | Número.Street number. | |
| bairro | string, máx. 100 | Bairro.Neighborhood. | |
| complemento | string, máx. 200 | Complemento.Address complement. | |
| ie | string, máx. 20 | Inscrição estadual.State tax registration. | |
| im | string, máx. 20 | Inscrição municipal.Municipal tax registration. | |
| caepf | string, máx. 14 | CAEPF. | |
| exterior_cidade | Condicional (exterior)Conditional (foreign) | string, máx. 60 | Obrigatória quando o tomador é estrangeiro.Required when the customer is foreign. |
| exterior_provincia | Condicional (exterior)Conditional (foreign) | string, máx. 60 | Obrigatória quando o tomador é estrangeiro.Required when the customer is foreign. |
nao_nif). O campo tipo não é enviado; o sistema o determina.
Identification: a CPF/CNPJ, NIF, or a no-NIF flag (nao_nif) must be present. The tipo field is not sent; the system determines it.
{
"codigo": 200,
"descricao": "Tomador cadastrado com sucesso.",
"tomador": {
"razao_social": "Empresa Exemplo LTDA",
"cpf_cnpj": "12345678000190",
"pais": "Brasil",
"cidade": "Salvador",
"endereco": "Av. Exemplo"
"...": "demais campos do cadastro"
}
}
9Consulta de tomadoresCustomer lookup
Endpoint:Endpoint: GET /api/v1/{ambiente}/tomadores
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| nome | OpcionalOptional | string, máx. 100 | Pesquisa por LIKE em razão social ou fantasia.Searches legal/trade name using LIKE. |
| documento | OpcionalOptional | string, máx. 40 | Pesquisa exata por CPF/CNPJ (normalizado) ou NIF.Exact search by (normalized) CPF/CNPJ or NIF. |
| cpf_cnpj / nif | Aceitos, sem efeitoAccepted, no effect | string |
Aceitos pela API, mas sem efeito na busca. Use documento.
Accepted by the API, but have no effect on the search. Use documento instead.
|
{
"codigo": 200,
"mensagem": "Tomadores encontrados.",
"total": 1,
"tomadores": [
{ "razao_social": "Empresa Exemplo LTDA", "...": "demais campos" }
]
}
10Emissão / cadastro de NFS-eInvoice issuance
Endpoint:Endpoint: POST /api/v1/{ambiente}/nfse
cidade, cidade_gerador e cidade_incidencia recebem o código IBGE do município. Os campos uf/uf_gerador/uf_incidencia são aceitos no payload, mas não são utilizados. Podem ser omitidos.
The cidade, cidade_gerador and cidade_incidencia fields take the municipality's IBGE code. The uf/uf_gerador/uf_incidencia fields are accepted in the payload but are not used. They can be omitted.
Identificação e serviçoIdentification & service
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| documento_tomador | string, máx. 40 | CPF/CNPJ ou NIF do tomador, já cadastrado.Customer's CPF/CNPJ or NIF, already registered. | |
| competencia | YYYY-MM | Competência (validação estrita de formato).Reference month (strict format validation). | |
| dps_emitente | integer | Emitente da DPS.DPS issuer. | |
| nsu | integer ou null | NSU; nullable. | |
| documento_intermediario | string, máx. 40 | Documento do intermediário (também deve estar cadastrado como tomador).Intermediary's document (must also be registered as a customer). | |
| item_servico_nacional | string, 6 caracterescharacters | Código do item nacional (desdobro diferente de "00").National service item code (breakdown other than "00"). | |
| item_servico_municipal | string, 6 caracterescharacters | Código do item municipal.Municipal service item code. | |
| nbs | string, máx. 15 | Código NBS existente na base.NBS code that exists in the database. |
LocalizaçãoLocation
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| cidade | string/integer (código IBGEIBGE code) | Cidade da prestação.City where the service was rendered. | |
| uf | Aceito, sem usoAccepted, unused | Não validado nem utilizado pelo resolver atual.Not validated nor used by the current resolver. | |
| cidade_gerador | string/integer (código IBGEIBGE code) | Cidade do fato gerador.City of the taxable event. | |
| uf_gerador | Aceito, sem usoAccepted, unused | Não validado nem utilizado pelo resolver atual.Not validated nor used by the current resolver. | |
| cidade_incidencia | string/integer (código IBGEIBGE code) | Cidade de incidência.City of tax incidence. | |
| uf_incidencia | Aceito, sem usoAccepted, unused | Não validado nem utilizado pelo resolver atual.Not validated nor used by the current resolver. |
Tributação e valoresTaxation & amounts
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| trib_issqn | integer | Tributação ISSQN.ISSQN taxation. | |
| exig_susp_tipo | integer | Tipo de suspensão.Suspension type. | |
| exig_susp_numero_processo | string | Número do processo.Case number. | |
| tipo_imunidade | integer | Tipo de imunidade.Immunity type. | |
| trib_aliquota | numeric | Alíquota de tributação.Taxation rate. | |
| tipo_retencao | integer | Tipo de retenção.Withholding type. | |
| valor_servico | numeric ≥ 0 | Valor do serviço.Service amount. | |
| valor_deducoes | numeric ≥ 0 | Deduções.Deductions. | |
| base_calculo | numeric ≥ 0 | Base de cálculo.Tax base. | |
| valor_iss | numeric ≥ 0 | ISS. | |
| aliquota | numeric ≥ 0 | Alíquota.Rate. | |
| valor_inss | numeric ≥ 0 | INSS. | |
| valor_irrf | numeric ≥ 0 | IRRF. | |
| valor_csll | numeric ≥ 0 | CSLL. | |
| valor_cofins | numeric ≥ 0 | COFINS. | |
| valor_pis | numeric ≥ 0 | PIS. | |
| outras_retencoes | numeric ≥ 0 | Outras retenções.Other withholdings. | |
| desconto_condicionado | numeric ≥ 0 | Desconto condicionado.Conditional discount. | |
| desconto_incondicionado | numeric ≥ 0 | Desconto incondicionado.Unconditional discount. |
Benefício municipal e RPSMunicipal benefit & RPS
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| bm_tipo | integer | Tipo do benefício.Benefit type. | |
| bm_valor | numeric ≥ 0 | Valor do benefício.Benefit amount. | |
| bm_percentual | numeric ≥ 0 | Percentual.Percentage. | |
| bm_numero | string | Número do benefício.Benefit number. | |
| rps_tipo | integer | Tipo do RPS.RPS type. | |
| rps_numero | string | Número do RPS.RPS number. | |
| rps_serie | string | Série.Series. | |
| rps_emissao | YYYY-MM-DD HH:MM:SS | Emissão do RPS.RPS issuance date. |
Dados adicionais da prestaçãoAdditional service data
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| modo_prestacao | integer | Modo de prestação.Service delivery mode. | |
| vinculo_prestacao | integer | Vínculo.Relationship. | |
| tipo_moeda | string, 3 | Código da moeda.Currency code. | |
| valor_serv_moeda | numeric ≥ 0 | Valor na moeda.Amount in that currency. | |
| mec_afcomexp | string, máx. 2 | Mecanismo AFComExp. | |
| mec_afcomext | string, máx. 2 | Mecanismo AFComExt. | |
| mov_temp_bens | integer | Movimentação temporária de bens.Temporary movement of goods. | |
| mdic | integer | Indicador MDIC.MDIC indicator. | |
| isadppu_categoria | integer | Categoria ADPPU.ADPPU category. | |
| isadppu_objeto | integer | Objeto ADPPU.ADPPU object. | |
| tipo_servico | integer | Tipo do serviço.Service type. |
Obra, evento e endereço da prestaçãoConstruction site, event & service address
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| obra_codigo | string, máx. 30 | Código da obra.Construction site code. | |
| obra_cib | string, máx. 8 | CIB. | |
| evento_nome | string, máx. 255 | Nome do evento.Event name. | |
| evento_data_inicio | YYYY-MM-DD | Início.Start date. | |
| evento_data_fim | YYYY-MM-DD | Fim.End date. | |
| evento_id | string, máx. 30 | ID do evento.Event ID. | |
| servico_cep | string, máx. 8 | CEP. | |
| servico_logradouro | string, máx. 255 | Logradouro.Street. | |
| servico_numero | string, máx. 60 | Número.Number. | |
| servico_complemento | string, máx. 156 | Complemento.Complement. | |
| servico_bairro | string, máx. 60 | Bairro.Neighborhood. | |
| servico_cep_exterior | string, máx. 11 | Código postal exterior.Foreign postal code. | |
| servico_cidade_exterior | string, máx. 60 | Cidade exterior.Foreign city. | |
| servico_provincia_exterior | string, máx. 60 | Província exterior.Foreign province. |
Informações adicionais e deduçõesAdditional info & deductions
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| descricao_servicos | string, 5–2000 | Discriminação dos serviços prestados.Description of the services rendered. | |
| documento_tecnico | string, máx. 40 | Documento técnico associado.Associated technical document. | |
| informacoes_complementares | string | Informações complementares livres.Free-form additional information. | |
| deducoes | array | Lista de deduções/documentos de fornecedores.List of deductions/supplier documents. | |
| deducoes.*.documento_fornecedor | string, máx. 40 | Documento do fornecedor (deve estar cadastrado como tomador).Supplier's document (must be registered as a customer). | |
| deducoes.*.tipo_documento | Sim (por item)Yes (per item) | integer | Tipo do documento da dedução.Deduction document type. |
| deducoes.*.nota_chave | string, máx. 50 | Chave da nota deduzida.Key of the deducted invoice. | |
| deducoes.*.valor_deducao | numeric ≥ 0 | Valor da dedução.Deduction amount. | |
| deducoes.*.valor_dedutivel | numeric ≥ 0 | Valor dedutível.Deductible amount. | |
| deducoes.*.data_emissao_doc | YYYY-MM-DD | Data de emissão do documento.Document issuance date. |
{
"codigo": 200,
"mensagem": "NFS-e processada com sucesso.",
"nfse": {
"numero": "000123",
"chave": "...",
"codigo_verificacao": "...",
"competencia": "2026-09",
"emissao": "2026-09-28 17:05:00",
"status": 1,
"dps_numero": "...",
"dps_chave": "..."
}
}
Campo status: 1 = Emitida, 2 = Cancelada.status field: 1 = Issued, 2 = Cancelled.
11Cancelamento de NFS-eInvoice cancellation
O cancelamento é realizado pela chave da NFS-e e exige autenticação Bearer.Cancellation is performed using the invoice key and requires Bearer authentication.
RotasRoutes
| MétodoMethod | Endpoint | AmbienteEnvironment |
|---|---|---|
| POST | /api/v1/sandbox/nfse/{chave}/cancelar | Sandbox |
| POST | /api/v1/production/nfse/{chave}/cancelar | ProduçãoProduction |
{chave} deve ser substituído pela chave da NFS-e que será cancelada.must be replaced with the key of the invoice to be cancelled.
Campos enviados no corpoBody fields
| ParâmetroParameter | ObrigatórioRequired | Tipo / formatoType / format | DescriçãoDescription |
|---|---|---|---|
| motivo_cancelamento | integer | 1: Erro na emissão 2: Serviço não prestado 9: Outros1: Issuance error 2: Service not rendered 9: Other |
|
| descricao_motivo_cancelamento | string, máx. 255 | Descrição obrigatória do motivo do cancelamento.Required description of the cancellation reason. |
Regras de cancelamentoCancellation rules
| CondiçãoCondition | RespostaResponse |
|---|---|
| NFS-e não pertence ao contribuinte autenticado ou não existeInvoice doesn't belong to the authenticated taxpayer, or doesn't exist | codigo 203 (HTTP 404) |
| NFS-e já está canceladaInvoice is already cancelled | codigo 203 (HTTP 422) |
| NFS-e vinculada a um DAM com cota em situação 1 ou 2Invoice linked to a DAM with an installment in status 1 or 2 | codigo 203 (HTTP 422) |
| SucessoSuccess | codigo 200 (HTTP 200) |
{
"codigo": 200,
"mensagem": "NFS-e cancelada com sucesso.",
"nfse": {
"numero": "000123",
"chave": "...",
"status": 2
}
}
12Códigos de retornoResponse codes
Todas as respostas trazem um campo codigo no corpo, além do HTTP status. Estes dois valores nem sempre coincidem.Every response carries a codigo field in the body, besides the HTTP status. These two values don't always match.
| codigo | HTTP | SignificadoMeaning | Onde ocorreWhere it happens |
|---|---|---|---|
| 200 | 200 | SucessoSuccess | Todas as operações concluídas com êxito.All successfully completed operations. |
| 204 | 200 | Tomador já existente (não é erro)Customer already exists (not an error) | Cadastro de tomador, quando já há um registro com o mesmo documento.Customer registration, when a record with the same document already exists. |
| 201 | 401 | Token ausente ou inválidoMissing or invalid token | Qualquer endpoint autenticado, via ApiTokenMiddleware.Any authenticated endpoint, via ApiTokenMiddleware. |
| 202 | 401 | Token expiradoExpired token | ApiTokenMiddleware, quando expires_at já passou.when expires_at has already passed. |
| 203 | 404 ouor 422 | Erro de validação ou de regra de negócioValidation or business-rule error | Payload inválido, entidade/ambiente inválidos, NFS-e não encontrada (404), já cancelada, vinculada a DAM.Invalid payload, invalid entity/environment, invoice not found (404), already cancelled, linked to a DAM. |
| 205 | 503 | Serviço bloqueado administrativamenteAdministratively blocked service | CheckBloqueioApi e bloqueio específicoand specific block nfse-notas. |
| 401 | 401 | Credenciais inválidas na geração do tokenInvalid credentials when generating the token | Exclusivo deExclusive to POST /auth/token. |
| 500 | 500 | Erro interno não tratadoUnhandled internal error | Falha de conexão com o banco da entidade, ou exceção inesperada.Entity database connection failure, or an unexpected exception. |
/auth/token usa codigo 401, enquanto a falta/invalidez de token nas demais rotas usa codigo 201. Ambas resultam em HTTP 401. Decida o fluxo pelo HTTP status combinado com a rota chamada.
Real inconsistency observed: an auth failure on /auth/token uses codigo 401, while a missing/invalid token on other routes uses codigo 201. Both result in HTTP 401. Branch your logic on the HTTP status combined with the called route.
Status da APIAPI Status
Verificação rápida de disponibilidade do ambiente Sandbox, feita diretamente do seu navegador. Quick availability check for the Sandbox environment, performed directly from your browser.
/api/v1/sandbox/auth/token com um corpo vazio. Qualquer resposta HTTP (mesmo 422 de validação) confirma que a API está no ar; uma falha de rede indica indisponibilidade.
This checker sends a real request to /api/v1/sandbox/auth/token with an empty body. Any HTTP response (even a 422 validation error) confirms the API is up; a network failure indicates unavailability.