How to Use DecodeHash Free API with an API Key

Learn how to decode Mpesa hashes using our Free API with an API Key.

Introduction

Welcome to the DecodeHash Free API user guide for signed up users.

Whether you're integrating Mpesa hash decoding into your application or exploring our API's capabilities, this guide will walk you through the process step-by-step.

Getting Started

Here's how to start using the Free API to decode Mpesa hashes with an API Key:

  1. Sign up for a free account on DecodeHash.
  2. Once you've signed up, you will receive an email with a link to activate your account.
  3. Click the link in the email to activate your account. If you signed up using a Google account, you will not need to activate your account - your account will be automatically activated.
  4. You will be redirected to the Profile page.
  5. Click on the API Keys tab.
  6. Click on the Generate New API Key button.
  7. Enter a name for your API key. e.g Production API Key.
  8. Click on the Create API Key button.
  9. Your API key will be generated and displayed on the page.
  10. Copy the API key and save it somewhere safe.

Examples for Developers

Below are examples of sending a request to the API in various popular languages:


                  curl -X GET "https://decodehash.com/app/api/v1/decode-hash/freemium/some-sha-hash" \
                  -H "Accept: application/json" \
                  -H "Authorization: Bearer API_KEY"

                  

                import requests
                from typing import Optional
                from pydantic import BaseModel

                class DecodeHashResponseModel(BaseModel):
                    msisdn: Optional[str] = None
                    hash: Optional[str] = None
                    success: Optional[bool] = False
                    detail: Optional[str] = None

                SERVER = "https://decodehash.com"
                DECODEHASH_END_POINT = "/app/api/v1/decode-hash/freemium/"

                def get_msisdn(hash_str: str) -> DecodeHashResponseModel:
                    url = f"{SERVER}{DECODEHASH_END_POINT}{hash_str}"
                    headers = {"Accept": "application/json", "Authorization": "Bearer API_KEY"}

                    try:
                        response = requests.get(url, headers=headers)

                        data = response.json()

                        decode_hash_response_model = DecodeHashResponseModel(
                            detail=data.get("detail"),
                            msisdn=data.get("msisdn"),
                            hash=data.get("hash"),
                            success=("msisdn" in data)  # Determine success based on available data
                        )

                        return decode_hash_response_model

                    except requests.exceptions.RequestException as e:
                        print(f"Error fetching data: {e}")
                        return DecodeHashResponseModel(success=False)

                    except json.JSONDecodeError as e:
                        print(f"Error decoding JSON: {e}")
                        return DecodeHashResponseModel(success=False)

                # Test the function
                if __name__ == "__main__":
                    hash_str = "some-sha-hash"
                    get_msisdn_response = get_msisdn(hash_str)
                    print(f"Response model: {get_msisdn_response}")
                  

                  const axios = require('axios');

                  class DecodeHashResponseModel {
                      constructor(msisdn = null, hash = null, success = false, detail = null) {
                          this.msisdn = msisdn;
                          this.hash = hash;
                          this.success = success;
                          this.detail = detail;
                      }
                  }

                  const SERVER = "https://decodehash.com";
                  const DECODEHASH_END_POINT = "/app/api/v1/decode-hash/freemium/";

                  async function getMsisdn(hashStr) {
                      const url = `${SERVER}${DECODEHASH_END_POINT}${hashStr}`;
                      const headers = { "Accept": "application/json", "Authorization": "Bearer API_KEY" };

                      try {
                          const response = await axios.get(url, { headers });
                          const data = response.data;

                          const decodeHashResponseModel = new DecodeHashResponseModel(
                              data.msisdn,
                              data.hash,
                              "msisdn" in data,  // Determine success based on available data
                              data.detail
                          );

                          return decodeHashResponseModel;

                      } catch (error) {
                          console.error(`Error fetching data: ${error}`);
                          return new DecodeHashResponseModel();
                      }
                  }

                  // Test the function
                  (async () => {
                      const hashStr = "some-sha-hash";
                      const getMsisdnResponse = await getMsisdn(hashStr);
                      console.log(`Response model: ${JSON.stringify(getMsisdnResponse)}`);
                  })();

                    

                package main

                import (
                  "encoding/json"
                  "fmt"
                  "net/http"
                  "time"
                )

                type DecodeHashResponseModel struct {
                  Msisdn  *string `json:"msisdn"`
                  Hash    *string `json:"hash"`
                  Success bool    `json:"success"`
                  Detail  *string `json:"detail"`
                }

                const (
                  Server           = "https://decodehash.com"
                  DecodeHashEndPoint = "/app/api/v1/decode-hash/freemium/"
                )

                func getMsisdn(hashStr string) DecodeHashResponseModel {
                  url := Server + DecodeHashEndPoint + hashStr
                  client := &http.Client{Timeout: 10 * time.Second}
                  req, err := http.NewRequest("GET", url, nil)
                  if err != nil {
                    fmt.Printf("Error creating request: %v\n", err)
                    return DecodeHashResponseModel{Success: false}
                  }

                  req.Header.Set("Accept", "application/json")
                  req.Header.Set("Authorization", "Bearer API_KEY")

                  resp, err := client.Do(req)
                  if err != nil {
                    fmt.Printf("Error fetching data: %v\n", err)
                    return DecodeHashResponseModel{Success: false}
                  }
                  defer resp.Body.Close()

                  var data map[string]interface{}
                  if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
                    fmt.Printf("Error decoding JSON: %v\n", err)
                    return DecodeHashResponseModel{Success: false}
                  }

                  msisdn, _ := data["msisdn"].(string)
                  hash, _ := data["hash"].(string)
                  detail, _ := data["detail"].(string)
                  success := msisdn != ""

                  return DecodeHashResponseModel{
                    Msisdn:  &msisdn,
                    Hash:    &hash,
                    Success: success,
                    Detail:  &detail,
                  }
                }

                func main() {
                  hashStr := "some-sha-hash"
                  getMsisdnResponse := getMsisdn(hashStr)
                  responseJSON, _ := json.MarshalIndent(getMsisdnResponse, "", "  ")
                  fmt.Printf("Response model: %s\n", string(responseJSON))
                }

                  

Notes

The free API has a limit of 50 requests per day.

If you would like to increase your daily limit, please contact us.

Last updated 1 month ago

Was this article helpful?