Bird
Raised Fist0
FastAPIframework~20 mins

JWT token creation in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
JWT Token Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this FastAPI JWT token creation snippet?
Consider this FastAPI code that creates a JWT token. What does the token variable contain after running this code?
FastAPI
from fastapi import FastAPI
from jose import jwt

app = FastAPI()

SECRET_KEY = "mysecret"
ALGORITHM = "HS256"

payload = {"sub": "user123"}
token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

print(token)
AA string token encoded with HS256 containing the payload {"sub": "user123"}
BA dictionary with keys 'sub' and 'token'
CA bytes object representing the token
DAn error because jose.jwt.encode requires a list payload
Attempts:
2 left
💡 Hint
Remember jwt.encode returns a string token, not a dictionary or bytes.
📝 Syntax
intermediate
2:00remaining
Which option correctly creates a JWT token with expiration in FastAPI?
You want to create a JWT token that expires in 30 minutes. Which code snippet correctly adds the expiration claim?
FastAPI
from datetime import datetime, timedelta
from jose import jwt

SECRET_KEY = "secret"
ALGORITHM = "HS256"

expire = datetime.utcnow() + timedelta(minutes=30)
payload = {"sub": "user1", "exp": expire.timestamp()}
token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
AUse 'exp': expire.timestamp() in payload
BUse 'exp': expire in payload
CUse 'exp': str(expire) in payload
DUse 'exp': expire.isoformat() in payload
Attempts:
2 left
💡 Hint
JWT expects the 'exp' claim as a Unix timestamp (number), not a datetime object or string.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI JWT token creation code raise a TypeError?
Examine this code snippet. Why does it raise a TypeError when encoding the token? from jose import jwt payload = {"sub": "user1", "exp": 1680000000} secret = None token = jwt.encode(payload, secret, algorithm="HS256")
FastAPI
from jose import jwt

payload = {"sub": "user1", "exp": 1680000000}
secret = None

token = jwt.encode(payload, secret, algorithm="HS256")
ABecause the algorithm 'HS256' is invalid
BBecause the payload 'exp' value is an integer, it must be a string
CBecause the secret key is None, jwt.encode expects a string or bytes
DBecause the payload is missing the 'iat' claim
Attempts:
2 left
💡 Hint
Check the type of the secret key passed to jwt.encode.
state_output
advanced
2:00remaining
What is the value of 'decoded_payload' after decoding this JWT token?
Given this code, what does 'decoded_payload' contain? from jose import jwt SECRET_KEY = "key123" ALGORITHM = "HS256" payload = {"sub": "userX", "role": "admin"} token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) decoded_payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
FastAPI
from jose import jwt

SECRET_KEY = "key123"
ALGORITHM = "HS256"
payload = {"sub": "userX", "role": "admin"}
token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
decoded_payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
ARaises a JWTError because decode requires expiration claim
B{"sub": "userX", "role": "admin", "alg": "HS256"}
C{"sub": "userX"}
D{"sub": "userX", "role": "admin"}
Attempts:
2 left
💡 Hint
jwt.decode returns the original payload if the token is valid and secret matches.
🧠 Conceptual
expert
2:00remaining
Which statement about JWT token creation in FastAPI is true?
Select the correct statement about creating JWT tokens in FastAPI using the jose library.
AThe secret key can be any Python object; jose.jwt.encode will convert it automatically.
BThe 'exp' claim must be a Unix timestamp number; otherwise, token validation will fail.
CJWT tokens created with HS256 do not require a secret key for encoding.
DThe payload dictionary keys must be strings starting with 'jwt_' to be valid.
Attempts:
2 left
💡 Hint
Think about the standard JWT claims and their expected formats.

Practice

(1/5)
1. What is the main purpose of creating a JWT token in FastAPI?
easy
A. To style the user interface
B. To send emails automatically
C. To connect to a database
D. To securely store user information for authentication

Solution

  1. Step 1: Understand JWT token purpose

    JWT tokens are used to safely carry user data for authentication.
  2. Step 2: Identify correct use in FastAPI

    FastAPI uses JWT tokens to verify user identity securely.
  3. Final Answer:

    To securely store user information for authentication -> Option D
  4. Quick Check:

    JWT purpose = secure user info [OK]
Hint: JWT tokens are for secure user identity, not UI or DB [OK]
Common Mistakes:
  • Confusing JWT with UI styling or database connection
  • Thinking JWT sends emails
  • Assuming JWT stores passwords directly
2. Which of the following is the correct way to import the function to create JWT tokens in FastAPI using PyJWT?
easy
A. import jwt.encode
B. from fastapi import jwt_encode
C. from jwt import encode
D. from fastapi.security import create_jwt

Solution

  1. Step 1: Identify the JWT library used

    PyJWT is commonly used and provides an encode function imported as 'from jwt import encode'.
  2. Step 2: Check FastAPI imports

    FastAPI itself does not provide jwt_encode or create_jwt functions directly.
  3. Final Answer:

    from jwt import encode -> Option C
  4. Quick Check:

    PyJWT encode import = from jwt import encode [OK]
Hint: PyJWT encode is imported from jwt, not fastapi [OK]
Common Mistakes:
  • Trying to import JWT functions directly from FastAPI
  • Using incorrect import syntax
  • Confusing module names
3. Given this code snippet, what will be the output of the print(token) statement?
from jwt import encode

payload = {"user_id": 123}
secret = "mysecret"
algorithm = "HS256"
token = encode(payload, secret, algorithm=algorithm)
print(token)
medium
A. A JWT token string encoded with user_id 123
B. An error because algorithm parameter is missing
C. The original payload dictionary printed
D. None, because encode returns nothing

Solution

  1. Step 1: Understand encode function behavior

    The encode function creates a JWT token string from the payload using the secret and algorithm.
  2. Step 2: Analyze the code snippet

    Payload and secret are provided correctly, algorithm is set to HS256, so encode returns a JWT token string.
  3. Final Answer:

    A JWT token string encoded with user_id 123 -> Option A
  4. Quick Check:

    encode returns JWT string [OK]
Hint: encode returns a token string, not the original data [OK]
Common Mistakes:
  • Expecting encode to print the payload
  • Missing algorithm causes error (not true here)
  • Thinking encode returns None
4. Identify the error in this JWT token creation code snippet:
from jwt import encode

payload = {"user_id": 42}
secret = "secretkey"
token = encode(payload, secret)
print(token)
medium
A. Missing algorithm parameter causes an error
B. No error; code runs correctly
C. Secret key should be bytes, not string
D. Payload must be a string, not a dictionary

Solution

  1. Step 1: Check encode function requirements

    PyJWT's encode has a default algorithm='HS256', so it is not strictly required.
  2. Step 2: Analyze the code snippet

    The code calls encode with payload and secret; algorithm defaults to HS256, so it runs correctly and produces a token.
  3. Final Answer:

    No error; code runs correctly -> Option B
  4. Quick Check:

    Algorithm defaults to HS256 = no error [OK]
Hint: PyJWT encode defaults to HS256 algorithm [OK]
Common Mistakes:
  • Assuming algorithm defaults to HS256
  • Thinking payload must be string
  • Believing secret must be bytes
5. You want to create a JWT token in FastAPI that expires in 30 minutes. Which code snippet correctly adds the expiration time to the payload before encoding?
hard
A. payload = {"user_id": 1, "exp": datetime.utcnow() + timedelta(minutes=30)}
B. payload = {"user_id": 1, "exp": str(datetime.utcnow() + timedelta(minutes=30))}
C. payload = {"user_id": 1, "exp": time.time() + 1800}
D. payload = {"user_id": 1, "exp": datetime.now() + timedelta(minutes=30)}

Solution

  1. Step 1: Understand JWT expiration format

    The 'exp' claim must be a UTC datetime or a timestamp representing expiration time.
  2. Step 2: Evaluate each option

    payload = {"user_id": 1, "exp": datetime.utcnow() + timedelta(minutes=30)} uses datetime.utcnow() + timedelta for 30 minutes, which is correct. payload = {"user_id": 1, "exp": str(datetime.utcnow() + timedelta(minutes=30))} converts datetime to string, which is invalid. payload = {"user_id": 1, "exp": time.time() + 1800} uses time.time() but JWT expects datetime or timestamp as int, so this may cause issues. payload = {"user_id": 1, "exp": datetime.now() + timedelta(minutes=30)} uses datetime.now() which is local time, not UTC, causing potential errors.
  3. Final Answer:

    payload = {"user_id": 1, "exp": datetime.utcnow() + timedelta(minutes=30)} -> Option A
  4. Quick Check:

    Use UTC datetime for 'exp' claim [OK]
Hint: Use datetime.utcnow() + timedelta for expiration [OK]
Common Mistakes:
  • Using local time instead of UTC
  • Converting datetime to string for 'exp'
  • Using wrong time functions like time.time() without conversion