How to Set Up PyPI Trusted Publishing

Trusted Publishing lets a CI workflow upload to PyPI by exchanging a short-lived OpenID Connect token for upload rights, so there is no API token sitting in your repository secrets waiting to leak. The Python Packaging User Guide and PyPI's own documentation describe the mechanism; this is the condensed path for a project built in GitHub Actions.

What you need

Step 1: register the publisher on PyPI

In the project's settings on PyPI, open the publishing section and add a trusted publisher for GitHub, entering the repository owner, repository name, workflow file name and environment. For a brand-new project, PyPI supports a "pending" publisher, which reserves the name and creates the project on the first successful upload from that workflow.

Step 2: create a protected environment

In the repository settings, create the environment you named. Add required reviewers or restrict it to tags if you want a human approval before anything reaches PyPI. This is optional but cheap, and it means a compromised branch cannot publish on its own.

Step 3: write the workflow

name: release
on:
  push:
    tags: ["v*"]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      # (fetch the repository source first)
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: python -m pip install build
      - run: python -m build
      - uses: actions/upload-artifact@v4
        with: { name: dist, path: dist/ }
  publish:
    needs: build
    runs-on: ubuntu-latest
    environment: pypi
    permissions:
      id-token: write
    steps:
      - uses: actions/download-artifact@v4
        with: { name: dist, path: dist/ }
      - uses: pypa/gh-action-pypi-publish@release/v1

Splitting build and publish into two jobs keeps the id-token: write permission away from the step that runs your build tooling and third-party code. Only the small publish job can mint the token.

Step 4: remove the old token

Once a release has gone through, delete any project-scoped API token you used before, and remove it from repository secrets. Leaving it in place defeats much of the point.

Common mistakes

How to check it worked

Push a tag, watch both jobs succeed, and open the release on PyPI. The project's release page should show the files, and recent versions of the publish action also generate attestations that PyPI can display alongside them. If the upload fails with an authentication error, compare the four publisher fields character by character before changing anything else.

Related pages