DEV Community

vishal patidar
vishal patidar

Posted on

Generate API key in JavaScript, Ruby and Python

To access any application service sometimes we need an API key which is used to identify that only authorized users can access the service this API key could be in any format like hexadecimal and digits.

when a developer build an application (like a weather application) they have to generate a unique API key for all user who wants to access the service.

So How we can generate the API key?

It is quite easy to generate an API key in javascript, ruby, python or any other programming language we will use some library to generate random number strings.

Generate API key in Ruby


require 'securerandom'

SecureRandom.urlsafe_base64(size_of_string)

SecureRandom.urlsafe_base64(30)

#7o4ZvEldmQbdNTA7uPpVZL6YuPKn6HDk1uRL--dP

Enter fullscreen mode Exit fullscreen mode

Generate API key in JavaScript

To generate a random key in javascript there is two way

@supercharge/strings package

Install the npm package

npm i @supercharge/strings 
Enter fullscreen mode Exit fullscreen mode
const Str = require('@supercharge/strings')

const random = Str.random()  

const random_WithFiftySymbols = Str.random(50)  

console.log(random);

//kpHWxNZgrm7MbvrrHuLDY

console.log(random_WithFiftySymbols);

//QQh0eGOvxI16cZIXzIyZ2rsNfOk0AjclxYRLYxhZhzL5ZH_7gi
Enter fullscreen mode Exit fullscreen mode

By Node.js Crypto

To generate a random string by Node.js Crypto you don't need to download any additional package this module is come with node.js by default.

const Crypto = require('crypto')

function randomString(size = 30) {  
  return Crypto
    .randomBytes(size)
    .toString('base64')
    .slice(0, size)
}

console.log(randomString());

//UmjfVpC+d+6B2wZclWuz7BPePR6J9K
Enter fullscreen mode Exit fullscreen mode

Generate API key in Python

By using random and string module we can generate random key with latter and digits.

import random
import string

print(''.join(random.choices(string.ascii_letters + string.digits, k=30)))

#vPDLFZ6NPozGW5LhEJIirm4aPHHKmC
Enter fullscreen mode Exit fullscreen mode

Save this post βœ…

Do like 😊

Share it πŸ‘¨β€πŸ‘¨β€πŸ‘¦β€πŸ‘¦

Top comments (0)