skip to Main Content

I’m trying to use the Stability.ai API to generate Stable Diffusion AI images.

I got my API key from https://beta.dreamstudio.ai/membership?tab=apiKeys

I am following the textToImage docs here: https://api.stability.ai/docs#tag/v1alphageneration/operation/v1alpha/generation#textToImage

I’m trying to use PHP / cURL to generate an Image using the API

$url = 'https://api.stability.ai/v1alpha/generation/stable-diffusion-512-v2-0/text-to-image';

$data = array(
   "api_key_header_Authorization" => "sk-XXX"); // API key here

$data['text_prompts']['text'] = 'a happy robot';
$data['text_prompts']['weight'] = 1;


$postdata = json_encode($data);

$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);

Here is the response:

{"name":"decode_payload","id":"sDzSQ7y2","message":"json: cannot unmarshal object into Go struct field TextToImageRequestBody.text_prompts of type []*server.TextPromptRequestBody","temporary":false,"timeout":false,"fault":false}

I was hoping to get a success response.

2

Answers


  1. Chosen as BEST ANSWER

    As Foobar mentioned, I needed an array of objects.

    Now I have:

    $url = 'https://api.stability.ai/v1alpha/generation/stable-diffusion-512-v2-0/text-to-image';
    
    
    $headers = [
                'Authorization: sk-XXX', // API key
                'Accept: image/png',
            ];
    
    
    
    $data['text_prompts'] = $arr_of_obj = array(
      (object) [
        'text' => 'a happy robot',
        'weight' => 1
      ]);
    
    
    
    $postdata = json_encode($data);
    
    $ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $result = curl_exec($ch);
    curl_close($ch);
    print_r ($result);
    

    which returns the png data of generated AI image


  2. text_prompts must be an array of objects.

    $data['text_prompts'][0]['text'] = 'a happy robot';
    $data['text_prompts'][0]['weight'] = 1;
    

    See here:
    https://api.stability.ai/docs#tag/v1alphageneration/operation/v1alpha/generation#textToImage (The Box on the right side)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search