Cara Sederhana Membuat JWT di Framework FastAPI – Bagian 15. Panduan Belajar FastAPI Untuk Pemula

Posted by

In this tutorial, we will learn how to easily create JSON Web Tokens (JWT) in the FastAPI framework. JSON Web Tokens are a popular method for securely transmitting information between parties as a JSON object. FastAPI is a modern web framework for building APIs with Python. This tutorial will focus on creating JWT tokens using FastAPI for beginners.

Part 15: Learning FastAPI for Beginners

Step 1: Getting Started
Before we begin, make sure you have FastAPI installed in your Python environment. You can install FastAPI using pip by running the following command:

pip install fastapi

Step 2: Creating a FastAPI instance
First, let’s create a FastAPI instance in a Python file. We will also import the necessary dependencies for generating JWT tokens.

from fastapi import FastAPI
import jwt
from datetime import datetime, timedelta

app = FastAPI()

Step 3: Generating JWT Tokens
Next, let’s create a route in our FastAPI instance that generates JWT tokens. We will use the jwt library to encode a payload with a secret key and generate a token.

secret_key = "mysecretkey"

@app.get("/generate_token")
def generate_token():
    payload = {
        'sub': 'user_id',
        'exp': datetime.utcnow() + timedelta(minutes=30)
    }

    token = jwt.encode(payload, secret_key, algorithm='HS256')
    return {"token": token}

In this route, we create a payload with a subject (sub) and an expiration time (exp). We then encode the payload using the jwt library with our secret key and the HMAC algorithm.

Step 4: Verifying JWT Tokens
To verify JWT tokens in FastAPI, we can create another route that decodes and verifies the token using our secret key.

@app.get("/verify_token/{token}")
def verify_token(token: str):
    try:
        payload = jwt.decode(token, secret_key, algorithms=['HS256'])
        return {"valid": True, "user_id": payload['sub']}
    except jwt.ExpiredSignatureError:
        return {"valid": False, "error": "Token has expired"}
    except jwt.InvalidTokenError:
        return {"valid": False, "error": "Invalid token"}

In this route, we decode the token using the jwt library and verify its validity. If the token is valid, we return the decoded payload including the user ID. If the token has expired or is invalid, we return an error message.

Step 5: Running the FastAPI Server
Finally, we can run the FastAPI server to test our JWT token generation and verification routes. Save the Python file and run the following command:

uvicorn filename:app --reload

Replace filename with the name of your Python file. The FastAPI server will start running on http://127.0.0.1:8000 by default.

Step 6: Testing the Routes
Open a web browser or API client and navigate to http://127.0.0.1:8000/generate_token to generate a JWT token. Copy the token and test the verification route by navigating to http://127.0.0.1:8000/verify_token/{token} to verify the token.

Congratulations! You have successfully learned how to create and verify JWT tokens in FastAPI for beginners. FastAPI is a powerful and easy-to-use framework for building APIs with Python. Experiment with different payloads, expiration times, and secret keys to customize your JWT tokens. Happy coding!