eliseomartelli
HomeBlogPhotosAbout

Python

Quick & dirty

server.py
import json
import aiohttp
from aiohttp import web
import os
 
API_KEY = os.environ.get("API_KEY")
 
 
@web.middleware
async def api_key_middleware(
    request: web.Request,
    handler: web.RequestHandler,
) -> web.Response:
    api_key = request.headers.get("X-API-Key")
    if API_KEY != api_key:
        return web.Response(
            content_type="application/json",
            text=json.dumps({"error": "Invalid api key"}),
            status=400,
        )
    return await handler(request)
 
 
async def api_route(request: web.Request) -> web.Response:
    try:
        data = await request.json()
        name = data.get("name")
        if prompt:
            reponse = {
                "name": name
            }
            return web.Response(
                content_type="application/json", text=json.dumps(reponse)
            )
        return web.Response(
            content_type="application/json",
            text=json.dumps({"error": 'missing "name"'}),
            status=400,
        )
    except (aiohttp.payload.LookupError, json.JSONDecodeError):
        return web.Response(
            content_type="application/json",
            text=json.dumps({"error": "invalid json input"}),
            status=400,
        )
 
 
app = web.Application(middlewares=[api_key_middleware])
app.add_routes([web.post("/api", api_route)])
 
 
if __name__ == "__main__":
    web.run_app(app, port=8080)