Getting started overview

Beginning development with the Discord API involves several foundational steps: setting up a Discord account, creating a new application in the Discord Developer Portal, obtaining necessary credentials for authentication, and executing an initial API call. This process establishes the connection required for building custom bots, integrating server functionality, and implementing user authentication for Discord users Discord API documentation.

The Discord API primarily utilizes RESTful principles, allowing developers to interact with Discord's services via HTTP requests. Authentication typically involves either a bot token for bot accounts or OAuth2 for user-based applications Discord API reference overview. Understanding how to manage these credentials and make a basic request is critical for successful integration.

Here's a quick reference table outlining the initial steps:

Step What to Do Where
1. Create Discord Account Register for a personal Discord account (if you don't have one). Discord homepage
2. Access Developer Portal Navigate to the Discord Developer Portal. Discord Developer Portal Applications
3. Create New Application Register a new application, providing a name. Discord Developer Portal > Applications > New Application
4. Create Bot Account (Optional) If building a bot, add a bot user to your application. Discord Developer Portal > Your Application > Bot > Add Bot
5. Get Bot Token / OAuth2 Credentials Retrieve your bot's token or configure OAuth2 Redirect URIs and client secrets. Discord Developer Portal > Your Application > Bot (for token) or OAuth2 (for client ID/secret)
6. Invite Bot to Server (If applicable) Generate an OAuth2 URL to invite your bot to a Discord server. Discord Developer Portal > Your Application > OAuth2 > URL Generator
7. Make First API Request Send an authenticated HTTP request using your token or OAuth2. Your preferred HTTP client or programming language.

Create an account and get keys

  1. Create a Discord Account: If you do not already have a Discord user account, create one at the Discord website. This account will be used to access the Developer Portal.
  2. Access the Discord Developer Portal: Navigate to the Discord Developer Portal. Log in with your Discord user credentials.
  3. Create a New Application:
    • On the Applications page, click the "New Application" button.
    • Provide a name for your application and agree to the Discord Developer Terms of Service and Developer Policy Discord Application object documentation. Then click "Create."
  4. Generate Bot Token (for Bot Applications):
    • After creating your application, navigate to the "Bot" section in the left sidebar.
    • Click "Add Bot" and confirm. This will create a bot user associated with your application.
    • Under the "Token" section, click "Reset Token." Copy the displayed token immediately. This token acts as the API key for your bot and should be kept secure. Do not share it publicly, and treat it like a password to your bot. If lost, you will need to reset it again.
    • Optionally, configure Public Bot settings and Message Content Intent based on your bot's requirements. For most bots interacting with messages, the "Message Content Intent" will need to be enabled Discord Privileged Intents.
  5. Configure OAuth2 Credentials (for User Applications):
    • If your application will authenticate Discord users (e.g., a website logging in with Discord), navigate to the "OAuth2" section in the left sidebar.
    • Under "General," your "Client ID" is displayed. This is publicly shareable.
    • Under "Client Secret," click "Reset Secret" and copy the new secret. This secret, along with your Client ID, is used to exchange authorization codes for access tokens Discord OAuth2 documentation. Keep the client secret confidential.
    • Add "Redirect URIs" that Discord will redirect users to after successful authorization. These must be exact matches to the URIs your application uses.

Your first request

This section demonstrates how to make a basic API request using a bot token. For user-based OAuth2 flows, the process involves an additional authorization step before obtaining an access token Understanding OAuth 2.0 flows.

We will use the Discord API to fetch information about your bot's user account. This requires your bot token obtained in the previous step.

Endpoint: GET /users/@me

Base URL: https://discord.com/api/v10

HTTP Method: GET

Authentication: Authorization: Bot YOUR_BOT_TOKEN

Example using curl:

curl -X GET \
  "https://discord.com/api/v10/users/@me" \
  -H "Authorization: Bot YOUR_BOT_TOKEN"

Replace YOUR_BOT_TOKEN with the actual bot token copied from the Developer Portal. If successful, the API will return a JSON object containing details about your bot's user account, similar to this:

{
  "id": "YOUR_BOT_ID",
  "username": "YourBotName",
  "avatar": "null",
  "discriminator": "1234",
  "public_flags": 0,
  "flags": 0,
  "bot": true,
  "mfa_enabled": true,
  "locale": "en-US"
}

Example using JavaScript (Node.js with node-fetch):

First, install node-fetch if you haven't already: npm install node-fetch

const fetch = require('node-fetch');

const BOT_TOKEN = 'YOUR_BOT_TOKEN'; // Replace with your actual bot token

async function getBotUser() {
  try {
    const response = await fetch('https://discord.com/api/v10/users/@me', {
      method: 'GET',
      headers: {
        'Authorization': `Bot ${BOT_TOKEN}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    console.log('Bot user data:', data);
  } catch (error) {
    console.error('Error fetching bot user data:', error);
  }
}

getBotUser();

Example using Python (with requests library):

First, install requests if you haven't already: pip install requests

import requests

BOT_TOKEN = 'YOUR_BOT_TOKEN' # Replace with your actual bot token

def get_bot_user():
    headers = {
        'Authorization': f'Bot {BOT_TOKEN}',
        'Content-Type': 'application/json'
    }
    r = requests.get('https://discord.com/api/v10/users/@me', headers=headers)

    if r.status_code == 200:
        print('Bot user data:', r.json())
    else:
        print(f'Error fetching bot user data: {r.status_code} - {r.text}')

get_bot_user()

Common next steps

After successfully making your first API request, developers typically proceed with the following actions:

  1. Explore Advanced Endpoints: Review the Discord API reference documentation to understand the full range of available endpoints for managing channels, messages, guilds, users, and more. Key areas include the Channel API for message management and the Gateway API for real-time event handling.
  2. Implement a Discord Bot: If building a bot, invite your bot to a Discord server. Go to your application in the Developer Portal, navigate to "OAuth2" > "URL Generator." Select the "bot" scope and necessary permissions (e.g., "Send Messages"). Copy the generated URL and open it in your browser to authorize your bot to join a server Discord bot authorization flow.
  3. Utilize an Official or Community SDK: While direct HTTP requests are possible, using an SDK simplifies development significantly. Popular options include discord.js for JavaScript, discord.py for Python, and discordgo for Go. These libraries handle authentication, rate limiting, and provide abstractions for Discord objects and events.
  4. Handle Rate Limits: Discord API imposes rate limits to prevent abuse. Developers must design their applications to respect these limits by monitoring HTTP 429 "Too Many Requests" responses and implementing appropriate backoff strategies Discord rate limit documentation. SDKs often manage this automatically.
  5. Implement Webhooks: For specific use cases, such as sending automated messages to a channel without full bot functionality, Discord Webhooks can be a simpler alternative. They provide a URL to which an application can send JSON payloads to post messages.
  6. Secure Credentials: Ensure your bot tokens, client secrets, and other sensitive information are stored securely and not hardcoded directly into your application's source code. Environment variables or secure configuration management systems are recommended Azure Key Vault best practices.

Troubleshooting the first call

Encountering issues during the initial API call is common. Here are some troubleshooting steps:

  • 401 Unauthorized: This indicates an issue with your authentication token.
    • Check Token Accuracy: Double-check that you have copied the bot token exactly, without any extra spaces or missing characters.
    • "Bot" Prefix: Ensure your Authorization header includes the "Bot" prefix (e.g., Authorization: Bot YOUR_BOT_TOKEN).
    • Token Reset: If unsure, go to the Developer Portal, your application's "Bot" section, and reset the token. Copy the new token and try again.
    • Token Expiration: Bot tokens do not expire, but if you reset it, the old one becomes invalid.
  • 403 Forbidden: This typically means your bot lacks the necessary permissions to access the requested resource.
    • Bot Permissions: Verify that your bot has the required permissions enabled in the "Bot" section of the Developer Portal. For example, to read messages, it might need "Read Message History" or "Message Content Intent" enabled.
    • Server Permissions: If the bot is in a server, ensure it has the necessary roles and channel-specific permissions within that server.
    • Intents: For most bot functionality, especially involving messages, you will need to enable Privileged Gateway Intents like Message Content Intent in the Developer Portal under your bot's settings.
  • 400 Bad Request: The API request body or parameters are malformed.
    • JSON Formatting: Ensure any JSON payload sent in POST or PATCH requests is valid. Use a JSON linter to check.
    • Required Parameters: Verify that all required parameters for the specific endpoint are included in your request Discord API endpoint details.
    • Content-Type Header: For requests with a body, ensure the Content-Type: application/json header is set correctly.
  • 429 Too Many Requests: You have exceeded Discord's rate limits.
    • Wait and Retry: The API response headers (Retry-After) will often indicate how long to wait before retrying. Implement exponential backoff.
    • Utilize SDKs: Discord SDKs often include built-in rate limit handling, which can simplify management.
  • Network Issues: Verify your internet connection and ensure no firewall or proxy is blocking access to discord.com/api/v10.
  • Check Discord Status: Occasionally, Discord's API itself may experience outages. Check the Discord Status Page for any reported issues.