DEV Community

Arth
Arth

Posted on

User avatars for your next project in 1 API call

Serverless Userpics

Open-source code: Github
Try live: userpics.devclad.com

Background?

I had been using Dicebear avatars locally for my app (DevClad) but then I came across a better set of avatars by Craftworks.design (a free set) and thought I should use them for all my projects.

Gist of it

So, long story short, I created a Cloudflare R2 bucket, uploaded 100 avatars, created a serverless Go function using Vercel serverless functions and voila!

Run curl -XGET 'https://userpics.devclad.com/api/getpic' and instantly get a random user avatar URL.

Why a URL?

So- why a URL? Why not streamed bytes directly in response?

It works for everyone this way.

Case 1: Someone might be simply embedding the image. A permlink of the image is objectively better.
Case 2: Save it to your own S3 bucket.

How does it work

Case 1: curl -XGET 'https://userpics.devclad.com/api/getpic'
Case 2: An example in Python (specifically tailored for Django) that works with userpics.devclad.com

def random_avatar():
    name = str(uuid.uuid4())[:8]
    with open(f"media/avatars/{name}.png", "wb+") as f:
        url = requests.get("https://userpics.devclad.com/api/getpic")
        response = requests.get(url.text, stream=True)
        if not response.ok:
            raise Exception("Could not get avatar")
        for block in response.iter_content(1024):
            if not block:
                break
            f.write(block)
    return f"avatars/{name}.png"
Enter fullscreen mode Exit fullscreen mode

That's it. Feel free to open feature requests or whatever.
The repo is here - github.com/arthtyagi/serverless-userpics

Oldest comments (0)