Your Own name generator: 2 Tutorials on Using an AI Name Generator API

Why you should build a Name Generator

Name generators are an incredibly popular tool. Whether your customers are creating a new character for a video game or need a unique name for a new business, or just want to have a beautiful fantasy name, even names for babies are searched for online. Here are some numbers, according to Google keyword planner, on search volume as of today (March 14, 2023), so that you understand the opportunities lurking. These numbers are per month.

name generator100000 – 1 Mio.
fantasy name generator100000 – 1 Mio.
business name generator100000 – 1 Mio.
domain name generator10000 – 100000
pet name generator1000 – 10000
Search volume per month globally (google keyword planner)

There are a lot of variants of these keywords and others that have similar search volumes. Another niche would be creating names for story, book, or game content or even a baby name generator (according to ahrefs.com approx. 50k volume only in the united states).

Tl;dr: A name generator can provide instant inspiration and satisfy the needs of millions of customers. 

In this blog post, I’ll show you how to use a name generator API to create your name generator. I’ll provide examples for a web app and a discord bot, all using popular programming languages. By the end of this post, you’ll have the tools you need to build yourself an ai powered name generator. 

Why NameForge is the Ideal Solution for Your Name Generator Needs

NameForge is the ideal solution for your name generator needs because it provides a simple and efficient way to create unique and personalized names. With its API, you can generate names for characters, businesses, children, usernames, or anything else by simply describing the qualities you are looking for.

NameForge offers a wide range of endpoints to create single or double names of varying lengths, allowing you to customize your output based on your specific needs. The endpoints have clear parameter requirements, ensuring that your input is correctly formatted and that you receive a valid response.

NameForge’s success response includes a name field that contains the generated name(s) and an optional info field that provides additional information about your input or output. In case of an error, NameForge returns clear and detailed error responses, such as a 400 Bad Request when the query parameter length is exceeded or a 404 Not Found when the endpoint is incorrect.

In summary, NameForge offers a simple and effective way to generate unique and personalized names for various purposes, with clear and detailed responses in case of success or error. It’s the ideal solution for anyone looking for a reliable and efficient name generator API.

If you are interested in the requirements in name generator APIs have a look at my blog post here[TODO: link]

How to Create a Name Generator Web App Using NameForge API

This tutorial will teach you how to create a web application by using angular. The example will be minimalistic to give you a launching pad from where you can customize it to your (customer’s) needs. 

The code can be downloaded from github.

First, you have to install angular by following the instructions provided on the official website.

Now let’s start by opening a terminal of your choice and navigating to the location where you like your project to be. When you have reached the folder of your desire create the angular project by entering the following command:

ng new hephaestus-angular

When prompted with ‘Would you like to add Angular routing?’ pick ‘Yes’.

Next, you will be asked for the stylesheet format you would like to choose, I pick ‘scss’.

After angular has created the project structure for you. It should look something similar to this:

project-structure after creation

At this point, you can start your application with the command (in the project root):

ng serve --open

This will open the application for you, it will be reachable at http://localhost:4200. The application will look like this:

Angular default application

Our application should be able to retrieve user-supplied descriptions, send these to the NameForge API and redirect the output back to the user. To make such a workflow work we will create a Service with:

ng generate service name

This command will instruct our project to create the file srcappname.service.ts and configure it to be injectable. It does create some other settings but these are not important for now. Change the content of the name.service.ts file to look like this:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class NameService {
  constructor(private http: HttpClient) {}
  generateName(query: string, endpoint: string){
    const headers = new HttpHeaders()
        .set('X-RapidAPI-Key', '<YOUR API KEY>')
        .set('X-RapidAPI-Host', 'nameforge.p.rapidapi.com');
    const url = `https://nameforge.p.rapidapi.com/${endpoint}/${query}`;
    return this.http.get(url, { headers, withCredentials: true });
  }
}

Our service implementation needs the HttpClient. We have to import it in the app.module.ts file:

You will need to replace <Your API KEY> with an actual key, after you have signed up at https://rapidapi.com/ you need to subscribe for a plan of NameForge API. You can pick ‘Basic’ it is free of charge, you will have 5 requests to test the service, and you won’t be charged if you make more requests. After the subscription head over to the endpoints tab and have a look at an endpoint you will find your key in the place I blacked out in the image:

Your API-Key is where the blue color is.

Take this key and replace <Your API KEY>. Now we need the service to make http-requests therefore you will have to import the HttpClientModule. Open the srcappapp.module.ts file and import the mentioned module at the top and add it to the imports-array .

Import of the HttpClientModlue

Now that we have a Service, we want to use it. Let’s make the Service usable by changing the srcappapp.component.ts to look like this:

import { Component } from '@angular/core';
import { NameService } from './name.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  query: string = "Describe the name you are looking for...";
  name?: string;
  nameType: string = "single-name/medium";
  constructor(private nameService: NameService) {}
  generateName() {
    this.nameService.generateName(this.query, this.nameType).subscribe(
      (data: any) => {
        this.name = data.name;
      },
      (error) => {
        console.error(error);
        alert('Error occurred while generating name.');
      }
    );
  }
}

The default view angular creates for you has done its job and will be replaced by us. Change it by changing the srcappapp.component.html file. Delete everything within this file and replace it with this:

<div>
  <h1>Generate Name</h1>
  <div>
    <label for="query">Enter your query:</label>
    <input type="text" id="query" [(ngModel)]="query">
  </div>
  <div>
    <label for="nameType">Select name type:</label>
    <select id="nameType" [(ngModel)]="nameType">
      <option value="single-name/short">Single Name (Short)</option>
      <option value="single-name/medium">Single Name (Medium)</option>
      <option value="single-name/long">Single Name (Long)</option>
      <option value="double-name/short">Double Name (Short)</option>
      <option value="double-name/medium">Double Name (Medium)</option>
      <option value="double-name/long">Double Name (Long)</option>
    </select>
  </div>
  <button (click)="generateName()">Generate Name</button>
  <div *ngIf="name">
    <h2>Generated Name:</h2>
    <p>{{ name }}</p>
  </div>
</div>

Angular does hot reloads, which means if you change the code it will detect it and reload the server. Now it will show you some errors, that is because we have two-way-bindings that are not yet implemented. Let’s fix this!

Head over to the srcappapp.module.ts again like before we add a module this time around its the ‘FormsModule’ add it at the top of the file and in the imports-array.

Now let’s check the tool by entering a query. When clicking the ‘Generate Name’-Button you should get a name that will be displayed right under the Button. (see image below)

Example output

Troubleshooting

Sometimes applications, unfortunately, do crash. One source of error can be the API server if it is at its limits. You will receive an error like this:

{
    "headers": {
       ...
    },
    "status": 500,
    "statusText": "OK",
    "url": "https://nameforge.p.rapidapi.com/single-name/medium/Name%20of%20an%20ancient%20mystical%20smith",
    "ok": false,
    "name": "HttpErrorResponse",
    "message": "Http failure response for https://nameforge.p.rapidapi.com/single-name/medium/Name%20of%20an%20ancient%20mystical%20smith: 500 OK",
    "error": {
        "code": 500,
        "name": "Internal Server Error",
        "description": "The server encountered an internal error and was unable to complete your request. Either the server is overloaded or    there is an error in the application."
    }
}

You as the developer need to react to errors of this kind, maybe ask the user to try again. You won’t be charged if this kind of error happens! It will not count as a request to the NameForge-API.

While creating this tutorial I used the direct API address and did not use RapidApi which caused CORS exceptions. Browsers prevent Cross-Origin Resource Sharing (CORS) to protect users from malicious websites that could perform actions on their behalf without their knowledge or consent.

When a web page requests resources from a different origin (i.e., domain [NameForge]) than the one that served the page [your angular server], the browser must decide whether to allow the request or block it. If the resource owner has not explicitly allowed cross-origin requests from the requesting origin, the browser will block the request by default to prevent unauthorized access to sensitive data.

We can fix this by creating a cors-proxy. This will effectively make the client request the data from your angular server instead of directly accessing the NameForge-API, therefore the API request and the web contents originate from the same source.

If you are interested in the mechanics have a look at this beautiful blog post it helped me understand the problem.

Generally, if an error happens you will be prompted with an alert like this:

Alert prompting you for an exception

Then open your developer tools and have a look at the console. Find the error message and can investigate it.

Additional Notes

In a production environment, you won’t ever … ever put your API-Key in the typescript code, which will be running as javascript on the client machines. You have to come up with a solution for it. Furthermore, you may want to add some distinction between users to prevent ‘free’-users from accessing the precious ‘/single[ or double]-name/long’ endpoints.

How to Create a Name Generator Discord Bot Using NameForge API

This Tutorial will show you how to create a discord bot using Python as the programming language and connecting the discord api. After following the step-by-step instructions you will have created a bot that can be added to servers and answer user commands which generate names.

Ok let’s start by heading over to https://discord.com/developers/applications, if you haven’t created an account yet – do so! Now, under “Applications” in your developer portal click “New Application” in the top right corner. This will prompt you for a name, I will use hephaestus.

Naming your discord application

You will be redirected to the corresponding page. To create a bot click “Bot” on the lefthand side menu. You will find a view like this:

Maybe you have to add a bot to the application first. Discord will prompt you with this if needed. Please click “Reset Token” to obtain a developer token and store it somewhere safe. Attention: you will only be able to see it once. The token will be used to connect the discord API later.

Discord bots need permissions to operate otherwise they won’t be able to read messages for example. Make sure that the permissions are set as shown in the next image:

Discord bot permissions needed

You successfully have created the basis for your bot already, the bot has to dwell somewhere. If you have a Discord server already you can skip the next step. To create a server head over to the app. Click the +icon marked with an arrow in the image below.

The next steps are:

  1. Choose “Create My Own”
  2. Choose “For me and my friends”
  3. Enter a server name
  4. Click “create”

Ok, now we have created a discord server and registered a bot(application) we have to introduce them to each other. Therefore please visit your developer portal again and click “OAuth2” and then “URL Generator”.

Connect discord bot with the server via OAuth

If you check the “bot”-option it will open “BOT PERMISSIONS” below please pick the options shown in the next image.

Connect discord bot to server – permissions

Now copy the link below. Open it in a new tab and navigate through the instructions. Afterward, you will have successfully added the bot to your server and we can start with the coding!

import discord
import requests
class Hephaestus(discord.Client):
    # go to https://discord.com/developers/applications/
    # click "Bot" in the left menu
    # under "Build-A-Bot" you will see "Reset Token" if you forgot your token
    DISCORD_TOKEN: str = "<YOUR DISCORD TOKEN>"
    # go to https://rapidapi.com/materializethoughts/api/nameforge
    # have a look at the enpoints tab under "code snippets" you will find the headers definition
    # the field "X-RapidAPI-Key" has your key
    NAME_FORGE_TOKEN: str = "<YOUR RAPID API NAME FORGE TOKEN>"
    BASE_URL: str = "https://nameforge.p.rapidapi.com/"
    COMMAND_PREFIX: str = "!"
    CMD_KEY_NAME: str = "name"
    CMD_KEY_URL: str = "url"
    CMD_KEY_DESCRIPTION: str = "description"
    CMDS: list[dict] = [
      {
        CMD_KEY_NAME: "help",
        CMD_KEY_URL: "na",
        CMD_KEY_DESCRIPTION: "Help command, it will explain how to use this Bot."
      },
      {
        CMD_KEY_NAME: "snsh",
        CMD_KEY_URL: "single-name/short/",
        CMD_KEY_DESCRIPTION: "Request a single name defined by the query. Max query length is 25 characters."
      },
      {
        CMD_KEY_NAME: "snmd",
        CMD_KEY_URL: "single-name/medium/",
        CMD_KEY_DESCRIPTION: "Request a single name defined by the query. Max query length is 50 characters."
      },
      {
        CMD_KEY_NAME: "snlg",
        CMD_KEY_URL: "single-name/long/",
        CMD_KEY_DESCRIPTION: "Request a single name defined by the query. Max query length is 200 characters."
      },
      {
        CMD_KEY_NAME: "dnsh",
        CMD_KEY_URL: "double-name/short/",
        CMD_KEY_DESCRIPTION: "Request a double name defined by the query. Max query length is 25 characters."
      },
      {
        CMD_KEY_NAME: "dnmd",
        CMD_KEY_URL: "double-name/medium/",
        CMD_KEY_DESCRIPTION: "Request a double name defined by the query. Max query length is 50 characters."
      },
      {
        CMD_KEY_NAME: "dnlg",
        CMD_KEY_URL: "double-name/long/",
        CMD_KEY_DESCRIPTION: "Request a double name defined by the query. Max query length is 200 characters."
      }
    ]
    def get_command(self, command_name: str) -> dict:
        for cmd in Hephaestus.CMDS[1:]:
            if command_name == cmd[Hephaestus.CMD_KEY_NAME]:
                return cmd
        return None
    def is_valid_command(self, command_name: str)-> bool:
        command_names = [cmd[Hephaestus.CMD_KEY_NAME] for cmd in Hephaestus.CMDS]
        return command_name in command_names
    def make_request(self, endpoint, query) -> str:
        headers = {
          "X-RapidAPI-Key":Hephaestus.NAME_FORGE_TOKEN,
          "X-RapidAPI-Host": "nameforge.p.rapidapi.com"
        }
        url = f"{Hephaestus.BASE_URL}{endpoint}{query}"
        print(f"Will send request -> {url}")
        response = requests.get(url, headers=headers)
        # Parse the response and send the generated name back to the user
        name = None
        if response.status_code == 200:
            data = response.json()
            if " " in data["name"]:
                name_parts = data["name"].split()
                name = f"{name_parts[0]} {name_parts[1]}"
            else:
                name = data["name"]
        return name
    async def on_ready(self):
        print("Bot is ready")
    async def send_help_message(self, recipient):
        help_string = "Commands:n"
        for cmd in Hephaestus.CMDS[1:]:
            cmd_name = cmd[Hephaestus.CMD_KEY_NAME]
            cmd_description = cmd[Hephaestus.CMD_KEY_DESCRIPTION]
            example_usage = f"Example Usage: *{Hephaestus.COMMAND_PREFIX}{cmd_name} [query]*"
            example_output = "Output: The generated name will be sent as a response."
            help_string += f"**{Hephaestus.COMMAND_PREFIX}{cmd_name}** - {cmd_description}n"
            help_string += f"{example_usage}n"
            help_string += f"{example_output}nn"
        await recipient.send(help_string)
    async def work_on_command(self, cmd, query, author):
        command = self.get_command(cmd)
        name = self.make_request(command[Hephaestus.CMD_KEY_URL], query)
        if name is None:
            await author.send("Sorry could not generate a name. Please try again in a few minutes.")
            return
        output = f"Input: {query}n"
        output += f"Output: {name}n"
        await author.send(output)
    async def on_message(self, message):
        # block own messages
        if message.author == self.user:
            return
        print("Message received")
        print(message.content)
        if message.content.startswith(Hephaestus.COMMAND_PREFIX):
            req = message.content[1:]
            cmd = req.split(" ", 1)[0].lower()
            author = message.author
            if not self.is_valid_command(cmd):
                print(f"Unknown command ->{cmd}")
                await author.send(f"Unknown command. Have a look at the help with '{Hephaestus.COMMAND_PREFIX}{Hephaestus.CMDS[0][Hephaestus.CMD_KEY_NAME]}'")
                return
            try:
                if cmd == Hephaestus.CMDS[0][Hephaestus.CMD_KEY_NAME]:  # help
                    await self.send_help_message(author)
                else:
                    query = req.split(" ", 1)[1]
                    await self.work_on_command(cmd, query, author)
            except:
                print(f"Error missing query on command {message.content}")
                await message.author.send(f"You need to specify a query for the name generation to work. Have a look at the help with '{Hephaestus.COMMAND_PREFIX}{Hephaestus.CMDS[0][Hephaestus.CMD_KEY_NAME]}'")
                return
intents = discord.Intents.default()
intents.message_content = True
bot = Hephaestus(intents=intents)
bot.run(Hephaestus.DISCORD_TOKEN)

The code is quite simple, let me explain the important parts:

It creates a class called Hephaestus that inherits from the discord.Client which is empowering you to interact with the discord API. The Bot will be able to read and write messages. It will read the channels and your DMs. It will respond via direct messages – we could change this behavior easily.
You have to add your tokens for DISCORD_TOKEN and NAME_FORGE_TOKEN the comments explain where to find/retrieve them if you don’t know them yet. As of yet, the bot does offer a command for each endpoint of the API (CMDS-list) but you can of course add other commands or combine them as you like.

The purpose of the bot is to show you how easy the integration of my API is – once you have done the installation and configuration of the bot. You may want to expand on this. For example, maybe only specific users can interact with the bot or only premium members can use all commands. Or even restrict the use in a timely manner. A totally different approach would be to write the queries for your users and therefore set the tone of names and only offer commands like !fntsy which would return a fantasy name that has your defined qualities.

Conclusion and Benefits of Using NameForge API for Name Generation

In this blog post, we have discussed the benefits of building a name generator using an AI-powered name generator API like NameForge. We have shown that name generators are highly popular and in demand, with millions of searches made every month. We have also provided examples of how to use NameForge API to create a web app and a discord bot, all using popular programming languages.

We have highlighted that NameForge is an ideal solution for creating personalized and unique names for a variety of purposes, such as characters, businesses, children, usernames, and more. With its clear and detailed response, NameForge API offers a simple and effective way to generate names, with the ability to customize output based on specific needs.

We encourage readers to explore NameForge API and use it to create their name generator services. To help with this, we have provided links to the web app, android app, and discord bot examples for readers to try out.

In summary, NameForge API provides an excellent opportunity for developers to build name generator services, with a variety of use cases and customizable options. So why not get started today and create your name generator using NameForge API?

If you need inspiration on what you can do with my name generator API have a look at this post.

Affiliate Disclaimer:

This post may contain affiliate links. If you make a purchase through these links, I may earn a commission or receive other rewards. This comes at no extra cost to you. I only recommend products or services I believe in and appreciate your support in using these links to make purchases. Thank you!

2 thoughts on “Your Own name generator: 2 Tutorials on Using an AI Name Generator API”

Leave a Comment

Your email address will not be published. Required fields are marked *