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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay