from fastapi import FastAPI, Query from fastapi.responses import JSONResponse import wikipedia app = FastAPI( title="Wikipedia Lookup API", description="A simple API to look up Wikipedia URLs for any topic", version="1.0.0" ) @app.get("/") async def lookup_wikipedia(topic: str = Query(..., description="The topic to search for on Wikipedia")): """ Look up a Wikipedia URL for a given topic. Args: topic: The topic to search for Returns: JSON with the topic and its Wikipedia URL """ try: # Search for the topic and get the first result page = wikipedia.page(topic) wikipedia_url = page.url return JSONResponse( content={ "topic": topic, "url": wikipedia_url } ) except wikipedia.exceptions.DisambiguationError as e: # If there are multiple matches, use the first one page = wikipedia.page(e.options[0]) wikipedia_url = page.url return JSONResponse( content={ "topic": topic, "url": wikipedia_url } ) except wikipedia.exceptions.PageError: # If no page is found, return an error return JSONResponse( status_code=404, content={ "error": f"No Wikipedia page found for '{topic}'" } ) except Exception as e: return JSONResponse( status_code=500, content={ "error": f"An error occurred: {str(e)}" } ) @app.get("/health") async def health_check(): """Health check endpoint""" return {"status": "healthy"}