0

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 Answers2

1

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)

Foobar
  • 769
  • 1
  • 4
  • I replaced with $data['text_prompts'] = $arr_of_obj = array( (object) [ 'text' => 'a happy robot', 'weight' => 1 ]); which I believe works, but now I get a different error: {"name":"invalid_enum_value","id":"bxR1VkEh","message":"value of accept must be one of \"image/png\", \"application/json\" but got value \"\\\"image/png\\\"\"","temporary":false,"timeout":false,"fault":false} – slanginbits Jan 19 '23 at 16:52
  • @slanginbits Then setup `Accept` header in the right way. We can not discuss more error messages here. My answer, fixes your first error message. :-) – Foobar Jan 19 '23 at 16:59
0

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