Actual Code All articles
Compliance

Making Tax Digital Is Here: Wiring Up HMRC's API Without Losing a Weekend

Actual Code
Making Tax Digital Is Here: Wiring Up HMRC's API Without Losing a Weekend

Photo by Photo by Jakub Żerdzicki on Unsplash on Unsplash

Nobody puts 'HMRC API integration' on a conference slide. It is dull, fiddly, aggressively well-documented work with no architectural glamour whatsoever. It is also, for a UK developer, one of the more reliable ways to get paid in February.

With quarterly reporting now landed for sole traders and landlords above the income threshold, a lot of small accountancy practices are discovering that their spreadsheet-plus-email workflow has a deadline attached to it. That is your opening.

Step one: get in the sandbox before you get clever

Register an application on the HMRC Developer Hub. You get a client ID and secret, and two environments: sandbox at test-api.service.hmrc.gov.uk and production at api.service.hmrc.gov.uk. Stay in sandbox for a fortnight. It has test users and test National Insurance numbers, and it will let you file nonsense to your heart's content.

Pick the scopes narrowly. read:self-assessment and write:self-assessment cover most of what you need for quarterly updates. Asking for more than you use is a question you will have to answer later.

Step two: the OAuth2 dance, which is mostly about storage

It is a standard authorisation code flow. Your user clicks through to HMRC's grant screen, comes back to your redirect URI with a code, and you exchange it:

const body = new URLSearchParams({
  grant_type: 'authorization_code',
  client_id: process.env.HMRC_CLIENT_ID,
  client_secret: process.env.HMRC_CLIENT_SECRET,
  redirect_uri: 'https://app.example.co.uk/hmrc/callback',
  code
});

await fetch('https://test-api.service.hmrc.gov.uk/oauth/token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body
});

Access tokens last around four hours. Refresh tokens last a great deal longer, up to eighteen months of use, which sounds generous until you remember that a self-employed plumber will not log in every month and will expect the thing to still work in April.

The engineering problem here is not OAuth. It is tenancy. You are storing credentials per client, per HMRC identifier, and you had better encrypt them at rest, scope the refresh job carefully, and handle the case where a token refresh fails at 2am without waking anybody up. Handle invalid_grant as a normal, expected state — 'this user must reauthorise' — and surface it as a friendly banner, not a stack trace.

Step three: the headers that catch everyone out

HMRC mandates fraud prevention headers on every API call. Miss them, or send contradictory ones, and you get a 403 with a code that does not immediately tell you which header offended.

The set includes connection method, device identifier, user identifier, timezone, and a cluster of browser and vendor values. The rules are pedantic in ways that will bite you: values must be consistent across a session, the device ID must be stable and must not be the same for two different users, and you cannot simply hardcode a plausible-looking string in your mobile app and hope.

headers: {
  Authorization: `Bearer ${accessToken}`,
  Accept: 'application/vnd.hmrc.1.0+json',
  'Gov-Client-Connection-Method': 'WEB_APP_VIA_SERVER',
  'Gov-Client-Device-ID': deviceId,
  'Gov-Client-User-IDs': `app=${userId}`,
  'Gov-Client-Timezone': 'UTC+00:00',
  'Gov-Vendor-Product-Name': 'Example Books',
  'Gov-Vendor-Version': '1.4.2'
}

Test this in sandbox with real browsers and real mobiles, because the values have to describe the actual client, and a curl request will only prove that curl works.

Step four: idempotency, or why you never blind-retry a submission

A quarterly update is a POST to a period endpoint. If the connection drops after HMRC has accepted it, retrying can produce a duplicate or a rejection depending on where you are in the flow. So:

When the accountant edits a figure after you have filed

They will. Every single quarter, someone will find a receipt in a shoebox.

The good news is that MTD quarterly updates are cumulative within the tax year — a later submission for the same period supersedes the earlier one. So the workflow is: don't panic, don't try to patch the old one, submit the corrected period again and keep both versions in your own ledger with a note of who changed what and why.

What you must not do is quietly overwrite your local copy. If there is ever a disagreement about what was filed in August, the only thing that settles it is your own immutable record of submissions. Build that table on day one. It is five columns and it will save you an extremely unpleasant phone call.

The unglamorous truth

This work is well-documented, thoroughly sandboxed and entirely deterministic. HMRC publishes a spec, you follow it, it works. There is no clever architecture to argue about and almost nothing to blog about.

Which is precisely why it pays. The market is full of developers who would rather rewrite something in a new framework than read a vendor's PDF on header formats. Be the other sort. Charge properly, keep the receipts, and remember that your client's real deadline is not your sprint boundary — it is the seventh of August, and it does not move.

All Articles

Related Articles

The Horizon Inquiry Wrote Your Audit Trail Spec. You Should Read It.

The Horizon Inquiry Wrote Your Audit Trail Spec. You Should Read It.

The Free JSON That Runs Britain: Five Public APIs Worth Building On

The Free JSON That Runs Britain: Five Public APIs Worth Building On

Half a Day, One Keyboard and a Screen Reader: The Accessibility Audit Your Team Can Actually Finish

Half a Day, One Keyboard and a Screen Reader: The Accessibility Audit Your Team Can Actually Finish