You can download this code by clicking the button below.
This code is now available for download.
This code creates a web server using Aiohttp-web that provides a GET endpoint to return information about a random user.
Technology Stack : Aiohttp-web, aiohttp, asyncio, random
Code Type : Web Server
Code Difficulty : Intermediate
def fetch_random_user(session):
import aiohttp
from aiohttp import web
import asyncio
import random
async def get_random_user(request):
url = f"https://randomuser.me/api/?results=1"
async with session.get(url) as response:
return await response.json()
app = web.Application()
app.router.add_get('/random-user', get_random_user)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, 'localhost', 8080)
await site.start()
print("Server started on http://localhost:8080/random-user")
# Close server
await asyncio.sleep(10)
await runner.cleanup()
return "Server is running and you can fetch a random user at http://localhost:8080/random-user"