Next.js Discord

Discord Forum

Error using x-api-key with python server-less functions

Answered
Yellow-legged Gull posted this in #help-forum
Open in Discord
Yellow-legged GullOP
Hi all,

When I try to add in a x-api-key to my code it doesnt work and gives me a 405 error

Code below:
from http.server import BaseHTTPRequestHandler
import os
import json

# Your API key for authentication
API_KEY = 'my_api_key'  # replace it with your actual API KEY

class handler(BaseHTTPRequestHandler):

    def do_POST(self):
        if self.headers.get('x-api-key') != API_KEY:
            self.send_response(403)
            self.wfile.write('Unauthorized'.encode('utf-8'))
            return
        self.send_response(201)
        self.send_header('Content-type', 'text/plain')
        self.end_headers()
        self.wfile.write('Hello, post os json!'.encode('utf-8'))
        return


Any suggestions?
Answered by Yellow-legged Gull
I solved it. This is the working code:

from http.server import BaseHTTPRequestHandler
import json
API_KEY = "my_api_key"


class handler(BaseHTTPRequestHandler):
    def do_POST(self):
        # Check the headers for the correct API Key
        if self.headers.get('x-api-key') != API_KEY:
            self.send_response(403)  # Send forbidden status
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            return self.wfile.write(json.dumps({'error': 'Incorrect API Key'}).encode())
        self.send_response(201)  # Send forbidden status
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        return self.wfile.write(json.dumps({'good': 'it worked'}).encode())
View full answer

1 Reply

Yellow-legged GullOP
I solved it. This is the working code:

from http.server import BaseHTTPRequestHandler
import json
API_KEY = "my_api_key"


class handler(BaseHTTPRequestHandler):
    def do_POST(self):
        # Check the headers for the correct API Key
        if self.headers.get('x-api-key') != API_KEY:
            self.send_response(403)  # Send forbidden status
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            return self.wfile.write(json.dumps({'error': 'Incorrect API Key'}).encode())
        self.send_response(201)  # Send forbidden status
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        return self.wfile.write(json.dumps({'good': 'it worked'}).encode())
Answer