How do I create a GUID / UUID?
Generating a Globally Unique Identifier (GUID) or Universal Unique Identifier (UUID) in various programming environments is a common requirement, especially for applications needing unique identifiers that do not require a central authority to avoid duplication. Here’s how you can generate UUIDs in several popular programming languages:
Python
In Python, you can use the uuid
module to generate a UUID. Here’s an example using Python 3:
import uuid # Generate a UUID based on the host ID and current time (UUID1) uuid_one = uuid.uuid1() print(f"UUID1: {uuid_one}") # Generate a random UUID (UUID4) uuid_four = uuid.uuid4() print(f"UUID4: {uuid_four}")
JavaScript (Node.js)
For Node.js applications, you can use the uuid
library available via npm. First, install the library:
npm install uuid
Then, generate a UUID like so:
const { v4: uuidv4 } = require('uuid'); // Generate a random UUID (UUID4) const myUUID = uuidv4(); console.log(`UUID4: ${myUUID}`);
JavaScript (Browser)
For client-side JavaScript, you can still use the uuid
library. It can be included in your project via a CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.2/uuid.min.js"></script> <script> // Generate a random UUID (UUID4) const myUUID = uuid.v4(); console.log(`UUID4: ${myUUID}`); </script>
Java
In Java, you can generate a UUID using the java.util.UUID
class:
import java.util.UUID; public class Main { public static void main(String[] args) { // Generate a random UUID (UUID4) UUID uuid = UUID.randomUUID(); System.out.println("UUID4: " + uuid.toString()); } }
C#
In C#, UUIDs are termed as GUIDs (Globally Unique Identifiers), and you can generate them using the System.Guid
class:
using System; class Program { static void Main() { // Generate a new GUID Guid myGUID = Guid.NewGuid(); Console.WriteLine("GUID: " + myGUID.ToString()); } }
PHP
In PHP, there isn’t a built-in function to generate UUIDs until PHP 8.1. For versions before PHP 8.1, you would typically use a library. However, from PHP 8.1 onwards, you can use the uuid_create()
function from the uuid
PECL extension.
// Generate a random UUID (UUID4) $uuid = uuid_create(UUID_TYPE_RANDOM); echo "UUID4: " . $uuid;
Before PHP 8.1, you might use a composer package like ramsey/uuid
:
composer require ramsey/uuid
use Ramsey\Uuid\Uuid; $uuid = Uuid::uuid4(); echo "UUID4: " . $uuid->toString();
Conclusion
Generating UUIDs/GUIDs is supported across multiple programming platforms either natively or via third-party libraries. Choosing to use native functions or libraries depends on your application’s specific requirements and the language features available. UUIDs are crucial for any application needing unique identifiers without the complexity of managing uniqueness across a distributed system.
GET YOUR FREE
Coding Questions Catalog