Generate JWT Token for Apple Store Connect API using Python
Tags: webdev, showdev, python, code
Published: 2023-02-06 10:18:54

---
title: Generate JWT Token for Apple Store Connect API using Python
published: true
description: let's generate JWT Token to access Apple Store Connect and perform any task you do in Apple Developer website. 
tags: #webdev #showdev #python #code
cover_image: https://cdn.discordapp.com/attachments/997271873551351808/1072060553960374294/ericgit-me_a_apple_logo_and_JWT_key_is_trying_to_unlock_the_app_271a1cc1-c59e-413c-93c8-6fc470e71552.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-02-06 07:09 +0000
---

The Apple store Connect APIs is REST API that enables user to perform any task that you do in Apple developer website. Calling API requires JWT Token for authorization and you need to generate a JWT Token yourself based on few parameters.

### API Key

To generate an API key for [App Store Connect API](https://appstoreconnect.apple.com/), 
1) log in to App Store Connect and select "Users and Access". 

![Generate JWT Token for Apple Store Connect API using Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jlp0z9n2ws4rtyrc3zgw.png)


2) Click on the API Keys tab and Add (+) button to generate

![Generate JWT Token for Apple Store Connect API using Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ny0jckco5hpyg1dxpfji.png)

Enter a name for the key, and select a  role for the key under Access and click generate. 

![Generate JWT Token for Apple Store Connect API using Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5zi980yunxmg2utdrs7h.png)

you will a new key's information, including its name, key ID and download link


![Generate JWT Token for Apple Store Connect API using Python](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ya5nqt5njvqvgdw1q6jd.png)


Download the Private key and store it in safe place as it's available for download a single time.



### Generating JWT
In order to generate  JWT token, we need 3 things as shown in the above last image. 
1) Private key
2) Key ID
3) Issuer ID




#### 1) JWT Header
Now we need to create a Header for JWT:
- Algorithms: ES256 encryption (used to sign jwt)
- KEY ID: 2X9R4HXF34 (replace with your)
- TYPE: JWT
```json
{
    "alg": "ES256",
    "kid": "2X9R4HXF34",
    "typ": "JWT"
}
```

#### 2) Payload
The final and most important step is to configure the payload correctly:
- issuer id:(Your issuer_id)
- iat: creating time of token in UNIX format
- exp: expiration time UNIX format
- aud: "appstoreconnect-v1"
- scrop: (optional) A list of operation you want apple store connect to allow for this JWT Token

```json
{
    "iss": "69a6de95-023f-47e3-e053-12ljleio3kajvzbv",
    "iat": 1528407600,
    "exp": 1528408800,
    "aud": "appstoreconnect-v1",
    "scope": [
        "GET /v1/apps"
    ]
}
```




## Let's generate one

Here you would need to replace the priave_key with your own file (which you downloaded) and it will give you the JWT token for 19Min validity. 

**Note: however, if the token expiration time is above >= 20Min, you will get 401 Status Code**

```python
from datetime import datetime, timedelta
from time import time, mktime
import jwt

dt = datetime.now() + timedelta(minutes=19)

headers = {
    "alg": "ES256",
    "kid": "2X9R4HXF34", 
    "typ": "JWT",
}


payload = {
    "iss": "69a6de95-023f-47e3-e053-12ljleio3kajvzbv",
    "iat": int(time()),
    "exp": int(mktime(dt.timetuple())),
    "aud": "appstoreconnect-v1",
}


with open("AuthKey_2X9R4HXF34.p8", "rb") as fh: # Add your file
    signing_key = fh.read()

gen_jwt = jwt.encode(payload, signing_key, algorithm="ES256", headers=headers)

print(f"[JWT] {gen_jwt}")
# Output:
# eyJhbGciOiJFUzI1NiIsImvtpZCI6IlZaVjcxyOFdRMkEiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiI2vWE2ZGU5NS0wMjNmLTQ3ZTMtZTA1My01YjhjxN2MxMWE0ZDEiLCJpYXQiOjENzU2Njc4NTgsImV4cCI6MTY3NTY2OTA1OCwiYXVkIjoiYXBwc3RvcmVjb25uZWO0LXYxIn0.w_lBLz3UxZUbnXaydkRierf5tY92meyTKmVU1wBt5zJzJGp2UigLMwc9ZIMQEJ4Ns0IqpWIU2FJH4R0AZGxTzbQ

```




let's test it by queries all the apps in your apple store:

```python
try:
    r = requests.get("https://api.appstoreconnect.apple.com/v1/apps", headers=gen_jwt)
    print(f"[R] {r.json()}")
except Exception as e:
    logging.info(f"❌ Error occurred: {e}")
```



## Conclusion

With the Apple Store Connect API, You can do all:

- In-App Purchases and Subscriptions. Manage in-app purchases and auto-renewable subscriptions for your app.

- TestFlight. Manage beta builds of your app, testers, and groups.

- Xcode Cloud. Read Xcode Cloud data, manage workflows, and start builds.

- Users and Roles. Send invitations for users to join your team. Adjust their level of access or remove users.

- Provisioning. Manage bundle IDs, capabilities, signing certificates, devices, and provisioning profiles.

- App Metadata. Create new versions, manage App Store information, and submit your app to the App Store.

- App Clip Experiences. Create an App Clip and manage App Clip experiences.

- Reporting. Download sales and financial reports.

- Power and Performance Metrics. Download aggregate metrics and diagnostics for App Store versions of your app.

- Customer Reviews and Review Responses. Get the customer reviews for your app and manage your responses to the customer reviews.

get started and take control of your app.


I hope it made your day a little brighter. Thank you so much &&  Happy Coding!!