How do I add my Stack Overflow reputation as a live badge on GitHub?
Asked Answered
S

8

30

I am trying to add my Stack Overflow reputation as a live badge on my GitHub profile README.

First, I would need to somehow get my account information from Stack Overflow using some API. Next, I would need to extract the reputation and then pass it to another API which creates badges in Markdown.

Now, I have done some research and it seems like I am able to use the Stack Exchange API to attain my Stack Overflow account information in JSON format via an endpoint URL. Furthermore, Shield.io's API will allow me to create badges from an endpoint URL which is perfect. However, Shields.io requires the endpoint to be in a specific JSON format.

So now to solve the puzzle, I need a third API which would be able to read and parse the JSON from the Stack Exchange API and then host an endpoint URL in the JSON format needed. RunKit's API seems to be able to do just that.

An example of what I am trying to achieve (but instead of commits it is my Stack Overflow reputation):

enter image description here

Stride answered 12/8, 2020 at 12:25 Comment(0)
S
11

First using stack exchange's user api here, you are able to attain your stack overflow account information in JSON format via an endpoint url. All you have to do is to specify your stack overflow user id in the id field and click run to generate the endpoint path. You can attain your stack overflow user id by clicking on your profile picture, it will then appear in the search bar.

enter image description here

Append the path generated to https://api.stackexchange.com to form the endpoint url.

My stack exchange endpoint url: https://api.stackexchange.com/2.2/users/9133459?order=desc&sort=reputation&site=stackoverflow

Now that we have our stack overflow information in JSON format, we can proceed to parse it and create a new endpoint which meets shields requirements. To do that you would have to create an account with RunKit. Publish this piece of code on RunKit and make sure the node version is v4.9.1 (replace the url in the code with your own endpoint url generated previously):

// variables
var endpoint = require("@runkit/runkit/json-endpoint/1.0.0");
var fetch = require("node-fetch");
var url = "https://api.stackexchange.com/2.2/users/9133459?order=desc&sort=reputation&site=stackoverflow";
let settings = { method: "Get" };  

// main function
endpoint(module.exports, async function()
{
    try {
       await fetch(url, settings)
            .then(res => res.json())
            .then((json) => {
                reputation = json["items"][0].reputation;
                if (reputation >= 1000) {
                    reputation = reputation / 1000;
                    reputation = Math.floor(reputation * 10) / 10;
                    // if first decimal place is 0
                    if ((reputation * 10) % 10 == 0) {
                        // round to int
                        reputation = Math.round(reputation);
                    }
                    reputation = reputation.toString();
                    reputation += "K";
                }
        });    
    } catch(e) {
        return {
            "schemaVersion": 1,
            "label": "STACKOVERFLOW REPUTATION",
            "message": "API ERROR",
            "color": "FF0000",
            "labelColor": "black",
            "style": "for-the-badge"
        }
    }
    return {
        "schemaVersion": 1,
        "label": "STACKOVERFLOW REPUTATION",
        "message": reputation,
        "color": "FE7A16",
        "labelColor": "black",
        "style": "for-the-badge"
    }
})

After publishing, click on the endpoint hyperlink at the top of the RunKit page to view the endpoint url which you are going to pass to shields in order to create the badge.

Here is my runkit endpoint url: https://stack-overflow-reputation-ciqil1ej93hq.runkit.sh

Now, all that is left is to go to shields.io's JSON endpoint badge page here and paste the url as such:

enter image description here

Besides copying the badge url option, you are also given the option to copy the markdown version, copy it and paste it in your GitHub profile README.

Markdown Outcome:

Custom badge

Note: You can change the design of the badge by changing the JSON return statements in the RunKit code or overriding what you want to change in the JSON endpoint badge page. The attributes you can change are listed on the same page.

Stride answered 12/8, 2020 at 12:25 Comment(3)
is a great answer except the async/await then using callbacksGuinna
API ERROR IN 2021Cindy
Doesn't work in 2022. Problem after passung example code in RunKit: { "error": "initialization_error", "message": "There was an error initalizing your endpoint." }Melindamelinde
H
54

Another easy solution is to use the flair feature that's built into Stack Exchange:

  1. Edit your profile

  2. Click on "Flair" in the sidebar:

    Screenshot of sidebar menu with Flair selected

  3. Copy the HTML shown on that page and paste it into your README.md

By default, flair images look like this:

profile for Chris at Stack Overflow, Q&A for professional and enthusiast programmers

There are options on the flair page for changing the theme as well as showing data from just one site (e.g. Stack Overflow) or including reputation from all Stack Exchange sites where you have over 200 points.

Heterodox answered 12/8, 2020 at 16:18 Comment(0)
F
18

To get StackOverflow reputation as a live badge, just replace my user user id and name with yours!!

<a href="https://stackoverflow.com/users/10249156/wasitshafi" target="_blank">
<img alt="StackOverflow"
src="https://stackoverflow-badge.vercel.app/?userID=10249156" />
</a>

Result

enter image description here

Feathery answered 28/11, 2021 at 12:52 Comment(0)
S
11

First using stack exchange's user api here, you are able to attain your stack overflow account information in JSON format via an endpoint url. All you have to do is to specify your stack overflow user id in the id field and click run to generate the endpoint path. You can attain your stack overflow user id by clicking on your profile picture, it will then appear in the search bar.

enter image description here

Append the path generated to https://api.stackexchange.com to form the endpoint url.

My stack exchange endpoint url: https://api.stackexchange.com/2.2/users/9133459?order=desc&sort=reputation&site=stackoverflow

Now that we have our stack overflow information in JSON format, we can proceed to parse it and create a new endpoint which meets shields requirements. To do that you would have to create an account with RunKit. Publish this piece of code on RunKit and make sure the node version is v4.9.1 (replace the url in the code with your own endpoint url generated previously):

// variables
var endpoint = require("@runkit/runkit/json-endpoint/1.0.0");
var fetch = require("node-fetch");
var url = "https://api.stackexchange.com/2.2/users/9133459?order=desc&sort=reputation&site=stackoverflow";
let settings = { method: "Get" };  

// main function
endpoint(module.exports, async function()
{
    try {
       await fetch(url, settings)
            .then(res => res.json())
            .then((json) => {
                reputation = json["items"][0].reputation;
                if (reputation >= 1000) {
                    reputation = reputation / 1000;
                    reputation = Math.floor(reputation * 10) / 10;
                    // if first decimal place is 0
                    if ((reputation * 10) % 10 == 0) {
                        // round to int
                        reputation = Math.round(reputation);
                    }
                    reputation = reputation.toString();
                    reputation += "K";
                }
        });    
    } catch(e) {
        return {
            "schemaVersion": 1,
            "label": "STACKOVERFLOW REPUTATION",
            "message": "API ERROR",
            "color": "FF0000",
            "labelColor": "black",
            "style": "for-the-badge"
        }
    }
    return {
        "schemaVersion": 1,
        "label": "STACKOVERFLOW REPUTATION",
        "message": reputation,
        "color": "FE7A16",
        "labelColor": "black",
        "style": "for-the-badge"
    }
})

After publishing, click on the endpoint hyperlink at the top of the RunKit page to view the endpoint url which you are going to pass to shields in order to create the badge.

Here is my runkit endpoint url: https://stack-overflow-reputation-ciqil1ej93hq.runkit.sh

Now, all that is left is to go to shields.io's JSON endpoint badge page here and paste the url as such:

enter image description here

Besides copying the badge url option, you are also given the option to copy the markdown version, copy it and paste it in your GitHub profile README.

Markdown Outcome:

Custom badge

Note: You can change the design of the badge by changing the JSON return statements in the RunKit code or overriding what you want to change in the JSON endpoint badge page. The attributes you can change are listed on the same page.

Stride answered 12/8, 2020 at 12:25 Comment(3)
is a great answer except the async/await then using callbacksGuinna
API ERROR IN 2021Cindy
Doesn't work in 2022. Problem after passung example code in RunKit: { "error": "initialization_error", "message": "There was an error initalizing your endpoint." }Melindamelinde
P
10

This is not working anymore... Other solution, First using stack exchange's user API here, All you have to do is to specify your stack overflow user id in the id field and click run to generate the endpoint path. You can attain your stack overflow user id by clicking on your profile picture, it will then appear in the search bar.

Now, go to shields.io chat badge here and paste your url in the query section

enter image description here

in the query section you have to paste only the part that is after users/ eg:

This is a complete url:
/2.2/users/2096394?order=desc&sort=reputation&site=stackoverflow
you only need this part:
2096394?order=desc&sort=reputation&site=stackoverflow

So that way you can get your badged working properly.

Persis answered 20/10, 2020 at 2:41 Comment(4)
this gives "invalid parameter"Swett
@LalitVavdara they should have changed something that made this solution to failPersis
any other option ?Swett
@LalitVavdara I did a research and it works sometimes and sometimes show invalid parameter, i couldnt find any other solution apart from the other answers.Persis
T
6

For me Shields.io's StackExchange reputation endpoint is working fine. Here is an example:

It breaks sometimes. Probable Reason. (Fixed)

![](https://img.shields.io/stackexchange/stackoverflow/r/<user_id>?color=orange&label=reputation&logo=stackoverflow&style=for-the-badge&cacheSeconds=86400)

<!-- hyperlinked with alt text and title: -->

[![<user_name>'s Stack Overflow Reputation](https://img.shields.io/stackexchange/stackoverflow/r/<user_id>?color=orange&label=reputation&logo=stackoverflow&style=for-the-badge)](https://stackoverflow.com/users/<user_id> "<user_name>'s Stack Overflow Reputation")

Put whatever you want in place of <user_name>, but replace <user_id> in above with your StackOverflow user ID. You can get it by visiting your profile and checking the profile URL. It is of the form: https://stackoverflow.com/users/<user_id>/<user_name>

Brc-dd's Stack Overflow Reputation

You can customize the colors/text/logo in the above badge if you wish.

Transferase answered 24/7, 2021 at 11:28 Comment(3)
Still gives invalid parameter for meConifer
That link worked for me once but when I reload the page it says invalid parameters againConifer
@Conifer Yeah, I can see now, I cleared the cache, and its showing invalid parameters. github.com/badges/shields/issues/5415Transferase
I
2

@Chris' solution is the only one that seems to work at the time of answering to this. Given that, if the Flair you get from the StackOverflow Flair section doesn't seem all that good you can set the reputation manually as follows,

<!-- Add your profile URL below-->
<a href="https://stackoverflow.com/users/10883380/visal-rajapakse">
    <img src="https://img.shields.io/badge/Stack%20Overflow-802-F47F24">
                                                        <!-- ^ Change this to your reputation -->
</a>

The above will look like:

Iseult answered 20/9, 2021 at 18:5 Comment(2)
It's not the live-data solution we want, but it's the only one that works on this page right now, aside from "flair" which is really ugly.Aleishaalejandra
A logo can be added with img.shields.io/badge/Reputation-802-F47F24?logo=stackoverflowMidlothian
M
2

https://github.com/lowlighter/metrics can generate an SVG which can include a SO widget, and the SVG can be included in a GitHub profile README.md. It has several styles and the SO plugin has several configuration options, but nothing approaches a shield layout.

Luckily it can generate a lot of other formats, including raw JSON that could be used by other tools to render a shield layout.

To create a shield, we can use its markdown format, and supply a template markdown file.

Incorporating @Visal-rajapakse's answer, I use the following markdown in my TEMPLATE.md:

<a href="https://stackoverflow.com/users/{{ plugins.stackoverflow.user.id }}">
    <img src="https://img.shields.io/badge/Reputation-{{ plugins.stackoverflow.user.reputation }}-F47F24?logo=stackoverflow&style=flat-square" alt="StackOverflow">
</a>

To activate this, create a GitHub Action in your "special" username repo to run lowlighters' metrics tool on that template to generate the README.md

Here is my GitHub action. Substitute 'jayvdb' and '5037965' with your Github username and SO userid:

name: Metrics
on:
  # Schedule updates (once per day)
  schedule: [{cron: "0 1 * * *"}]
  # Lines below let you run workflow manually and on each commit (optional)
  workflow_dispatch:
  push: {branches: ["master", "main"]}

jobs:
  readme-template:
    name: Generate README
    runs-on: ubuntu-latest
    steps:
      - name: Update README.md
        uses: lowlighter/metrics@main
        with:
          # Common config
          user: jayvdb
          token: ${{ secrets.METRICS_TOKEN }}
          output_action: skip-if-only-metadata-changed
          committer_branch: main
          committer_message: Update ${filename} - [GitHub Action]
          config_timezone: Etc/UTC

          # Input file
          markdown: https://raw.githubusercontent.com/jayvdb/jayvdb/main/TEMPLATE.md

          # Output file
          template: markdown
          filename: README.md
          config_output: markdown

          plugin_stackoverflow: yes
          plugin_stackoverflow_user: 5037965
          plugin_stackoverflow_sections: answers-top, answers-recent
          plugin_stackoverflow_limit: 3
          plugin_stackoverflow_lines: 0

If you only want a SO widget, there are a few other readme widgets/generators with various builtin layouts, but none of them currently support a shield layout. They are easier to use, and the authors may be willing to adding a shield layout.

Midlothian answered 28/10, 2021 at 8:7 Comment(0)
B
1

There is https://shields.io/

Unfortunately is not working.

So I forked and cloned the shield repository. When I ran locally it worked. So this means that the StackOverflow API probably has quota or is blacklisting the shield IO ip address.

What you can do is to fork this project and host it yourself (you can use something like heroku).

Bloodshed answered 3/4, 2021 at 4:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.