API Code Examples

API Code Examples

This section provides examples of how to interact with the Meme Token Generator API using different programming languages and frameworks.

cURL Example

Here are several ways to use cURL to interact with the API:

Basic Request

curl -X POST \
  https://ai.justpump.pro \
  -H 'Content-Type: application/json' \
  -d '{
    "userDescription": "A token based on flying pandas eating bamboo in space"
  }'

Save Response to File

curl -X POST \
  https://ai.justpump.pro \
  -H 'Content-Type: application/json' \
  -d '{
    "userDescription": "A token based on flying pandas eating bamboo in space"
  }' \
  -o response.json

With Pretty Printing

curl -X POST \
  https://ai.justpump.pro \
  -H 'Content-Type: application/json' \
  -d '{
    "userDescription": "A token based on flying pandas eating bamboo in space"
  }' | json_pp

Windows Command Prompt

curl -X POST ^
  https://ai.justpump.pro ^
  -H "Content-Type: application/json" ^
  -d "{\"userDescription\": \"A token based on flying pandas eating bamboo in space\"}"

With Verbose Output

curl -v -X POST \
  https://ai.justpump.pro \
  -H 'Content-Type: application/json' \
  -d '{
    "userDescription": "A token based on flying pandas eating bamboo in space"
  }'

Example Response

{
  "success": true,
  "generated": "1. Name: GalactoCat\n2. Symbol: GCAT\n3. Total Supply: 1000000000\n4. Brief description: First feline-powered intergalactic cryptocurrency, enabling cosmic adventures for cats across the universe.\n5. Logo prompt: A cartoon cat in an astronaut helmet, floating in space with stars twinkling in background, wearing cool space goggles.",
  "timestamp": "2024-01-01T12:00:00Z"
}

Notes for cURL Usage

  1. Make sure to properly escape quotes in the JSON payload

  2. Use -v flag for debugging and seeing detailed request/response information

  3. Windows users should use ^ instead of \ for line continuation

  4. The -o flag can be used to save the response to a file

  5. Use json_pp or jq for prettier JSON output formatting

JavaScript / Node.js Example

Using the native fetch API to make requests to the endpoint.

async function generateMemeToken(description) {
  try {
    const response = await fetch('https://ai.justpump.pro', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        userDescription: description
      })
    });
    
    const data = await response.json();
    if (!data.success) {
      throw new Error(data.error);
    }
    return data;
  } catch (error) {
    console.error('Error generating meme token:', error);
    throw error;
  }
}

// Example usage
generateMemeToken('A token based on flying pandas eating bamboo in space')
  .then(result => {
    console.log('Generated Token:', result.generated);
    console.log('Timestamp:', result.timestamp);
  })
  .catch(error => {
    console.error('Failed:', error);
  });

Python Example

Using the requests library to interact with the API.

import requests
import json

def generate_meme_token(description):
    url = 'https://ai.justpump.pro'
    
    try:
        response = requests.post(
            url,
            headers={'Content-Type': 'application/json'},
            json={'userDescription': description}
        )
        response.raise_for_status()
        
        result = response.json()
        if not result.get('success'):
            raise Exception(result.get('error'))
        
        return result
    except requests.exceptions.RequestException as e:
        print(f'Error making request: {e}')
        raise
    except Exception as e:
        print(f'Error processing response: {e}')
        raise

# Example usage
try:
    result = generate_meme_token('A token based on surfing dogs riding cosmic waves')
    print('Generated Token:', result['generated'])
    print('Timestamp:', result['timestamp'])
except Exception as e:
    print('Failed:', e)

React/TypeScript Component Example

A complete React component with TypeScript support and error handling.

import React, { useState } from 'react';

interface TokenResponse {
  success: boolean;
  generated: string;
  timestamp: string;
}

const MemeTokenGenerator: React.FC = () => {
  const [description, setDescription] = useState('');
  const [result, setResult] = useState<TokenResponse | null>(null);
  const [error, setError] = useState<string>('');
  const [loading, setLoading] = useState(false);

  const generateToken = async () => {
    setLoading(true);
    setError('');
    try {
      const response = await fetch('https://ai.justpump.pro', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userDescription: description
        })
      });
      
      const data = await response.json();
      if (!data.success) {
        throw new Error(data.error);
      }
      
      setResult(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to generate token');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-4">
      <textarea
        value={description}
        onChange={(e) => setDescription(e.target.value)}
        placeholder="Enter token description..."
        className="w-full p-2 border rounded"
      />
      <button
        onClick={generateToken}
        disabled={loading || !description}
        className="mt-2 px-4 py-2 bg-blue-500 text-white rounded"
      >
        {loading ? 'Generating...' : 'Generate Token'}
      </button>
      
      {error && (
        <div className="mt-4 p-2 bg-red-100 text-red-700 rounded">
          {error}
        </div>
      )}
      
      {result && (
        <div className="mt-4 p-4 bg-gray-100 rounded">
          <pre>{result.generated}</pre>
          <p className="mt-2 text-gray-600">Generated at: {result.timestamp}</p>
        </div>
      )}
    </div>
  );
};

export default MemeTokenGenerator;

Example Response

Here's what a successful response looks like:

{
  "success": true,
  "generated": "1. Name: GalactoCat\n2. Symbol: GCAT\n3. Total Supply: 1000000000\n4. Brief description: First feline-powered intergalactic cryptocurrency, enabling cosmic adventures for cats across the universe.\n5. Logo prompt: A cartoon cat in an astronaut helmet, floating in space with stars twinkling in background, wearing cool space goggles.",
  "timestamp": "2024-01-01T12:00:00Z"
}

Error Handling

All examples include proper error handling for common scenarios:

  • Network errors

  • Invalid responses

  • API errors

  • Validation errors

Make sure to implement appropriate error handling in your production code.

Dependencies

  • Python: requests libraryExample Usage

    cURL

    curl -X POST \
      https://ai-image.justpump.pro \
      -H 'Content-Type: application/json' \
      -d '{
        "prompt": "A beautiful sunset over a mountain lake"
      }' \
      --output image.png

    JavaScript

    async function generateImage(prompt) {
      try {
        const response = await fetch('https://ai-image.justpump.pro', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ prompt })
        });
        
        if (!response.ok) {
          const error = await response.json();
          throw new Error(error.message || 'Failed to generate image');
        }
        
        // Response is a PNG image
        const imageBlob = await response.blob();
        return imageBlob;
      } catch (error) {
        console.error('Error:', error);
        throw error;
      }
    }
    
    // Example usage with HTML img element
    async function displayGeneratedImage(prompt) {
      try {
        const imageBlob = await generateImage(prompt);
        const imageUrl = URL.createObjectURL(imageBlob);
        const imgElement = document.createElement('img');
        imgElement.src = imageUrl;
        document.body.appendChild(imgElement);
      } catch (error) {
        console.error('Failed to generate image:', error);
      }
    }

    Python

    import requests
    
    def generate_image(prompt):
        url = 'https://ai-image.justpump.pro'
        
        try:
            response = requests.post(
                url,
                headers={'Content-Type': 'application/json'},
                json={'prompt': prompt}
            )
            response.raise_for_status()
            
            # Save the image
            with open('generated_image.png', 'wb') as f:
                f.write(response.content)
                
            return 'generated_image.png'
        except requests.exceptions.RequestException as e:
            print(f'Error generating image: {e}')
            raise
    
    # Example usage
    try:
        image_path = generate_image('A beautiful sunset over a mountain lake')
        print(f'Image saved to: {image_path}')
    except Exception as e:
        print(f'Failed: {e}')

    Error Handling

  • React: react and typescript

  • Node.js: No additional dependencies needed

Notes

  1. All examples assume you have the necessary dependencies installed

  2. ded for better development experience

  3. Examples include basic error handling and loading states

  4. All requests use the POST method with JSON content type

Additional Resources

Last updated