Use Postman or cURL to call image and video generation APIs
Este artigo descreve como usar o Postman e o cURL para chamar APIs de geração de imagem ou vídeo no Alibaba Cloud Model Studio (Bailian). Este guia utiliza um exemplo de text-to-image para demonstrar o processo completo, desde a criação da tarefa até a obtenção do resultado.
Postman: ferramenta gráfica e intuitiva para testar requisições HTTP. Recomendada para iniciantes.
cURL: ferramenta de linha de comando poderosa, ideal para desenvolvedores familiarizados com esse ambiente.
O Postman e o cURL destinam-se a testes rápidos e verificações funcionais. Em ambientes de produção, use os SDKs oficiais ou implemente suas próprias chamadas HTTP.
As tarefas de geração de imagem e vídeo podem demorar muito para serem concluídas, variando de mais de dez segundos a vários minutos. Para evitar conexões HTTP longas e timeouts, a API utiliza um mecanismo de chamada assíncrona. O processo divide-se em duas etapas:
Crie uma tarefa: chame a API para criar uma tarefa. O service retorna sincronamente um ID de tarefa (task_id).
Consulte o resultado: use o ID da tarefa para consultar o status periodicamente até a conclusão e, em seguida, obtenha a URL final da imagem ou do vídeo.
Use o seguinte comando cURL para configure o Postman.
A URL base a seguir refere-se à região Singapore. Use a URL base correspondente à sua região.
Copy
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \ -H 'X-DashScope-Async: enable' \ -H "Authorization: Bearer $DASHSCOPE_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "wan2.5-t2i-preview", "input": { "prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display" }, "parameters": { "size": "1024*1024", "n": 1 }}'
No Postman, clique em no botão new ou + para crie uma nova requisição e selecione HTTP como tipo de requisição.
No menu suspenso de método de requisição, selecione POST e insira a URL correspondente à região de implantação do seu modelo:
Singapore: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis. Substitua WorkspaceId pelo seu Workspace ID real, conforme descrito em Obter Workspace ID.
US (Virginia): https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
China (Beijing): https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
Para verificar os modelos suportados em cada região, consulte o console do Model Studio. A região atual e o escopo de implantação do service baseiam-se nas relações de vinculação predefinidas do sistema , não sendo suportadas combinações personalizadas.
Copy
POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
Clique em na aba Headers e adicione os três pares chave-valor a seguir.
Key
Value
Description
In Postman, on the Headers tab, defina X-DashScope-Async to enable, Authorization to Bearer <your-api-key>, and Content-Type to application/json.
X-DashScope-Async
ative
Enables asynchronous calls.
Authorization
Bearer sk-xxx (Replace sk-xxx with your API key)
Authentication credential.
Content-Type
application/json
Declares that the request body is in JSON format.
Configure o corpo da requisição:
Clique em na aba Body, selecione o botão de opção raw, escolha JSON no menu suspenso de formato à direita e cole o conteúdo JSON que segue -d no exemplo cURL dentro da caixa de entrada.
Copy
{ "model": "wan2.5-t2i-preview", "input": { "prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display" }, "parameters": { "size": "1024*1024", "n": 1 }}
(Opcional) Clique em em Beautify no lado direito da página para formatar o JSON e facilitar a leitura.
Clique em em Send para enviar a requisição e obter o task_id. O task_id é válido por 24 horas. Após esse período, não será possível consultar o resultado. Recupere o resultado prontamente.
Após obter o ID da tarefa, chame o endpoint de consulta para recuperar o resultado final.
Singapore: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis. Substitua WorkspaceId pelo seu Workspace ID real.
US (Virginia): https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
China (Beijing): https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
Copy
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Configure a requisição de consulta no Postman:
Crie uma nova requisição HTTP.
Defina o método de requisição como GET.
De acordo com a região, insira a URL de consulta e substitua {task_id} na URL pelo task_id real obtido na Etapa 1.
Na aba Headers, adicione o cabeçalho Authorization, utilizando a mesma chave de API da Etapa 1.
Clique em em Send.
Copy
GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/42442de9-917d-4c41-80a7-37fb7ad25ed2Headers:Cookie: acw_tc=896b2ccd-a0cd-40a8-a557-bb73cee5cf957...Postman-Token: <calculated when request is sent>Host: <calculated when request is sent>User-Agent: PostmanRuntime/7.49.1Accept: */*Accept-Encoding: gzip, deflate, brConnection: keep-aliveAuthorization: Bearer sk-xxx
Verifique a resposta. Consulte este endpoint periodicamente até que o task_status seja SUCCEEDED para obter a URL da imagem. A URL da imagem é válida por 24 horas. Certifique-se de baixe a imagem dentro desse prazo de validade.
Copy
"results": [ { "orig_prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display", "actual_prompt": "A cozy and elegant flower shop, with an exterior decorated with exquisitely carved windows. The window frames are light-colored wood, set with transparent glass that reveals the soft light inside. The front door is a beautiful solid wood door that retains its natural grain, complemented by a brass handle and a vintage nameplate, giving it a quaint and textured feel. On both sides of the front steps, and on the windowsills and entrance area, various flowers—including roses, lilies, hydrangeas, and tulips—are arranged in a staggered, vibrant display. Some bouquets are wrapped in kraft paper and tied with twine, exuding a fresh, natural scent. The background features a quiet European town streetscape, with stone-paved roads and greenery adding to the charm. The overall image is in a realistic photographic style, with soft lighting and a warm color palette that highlights the shop's exquisite and romantic atmosphere.", "url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1d/3a/20251203/7a2bee47/42442de9-917d-4c41-80a7-37fb7ad25ed2.png?xxx" } ]
Certifique-se de ter instale o cURL e configurado a chave de API como variável de ambiente, para referenciar diretamente a variável $DASHSCOPE_API_KEY posteriormente.
Verificar se o cURL está instalado
Execute o seguinte comando para verificar se o cURL está instalado.
Copy
curl --version
Se você vir uma saída semelhante à seguinte, o cURL está instalado:
A URL base a seguir refere-se à região Singapore. Use a URL base correspondente à sua região.
Copy
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \ -H 'X-DashScope-Async: enable' \ -H "Authorization: Bearer $DASHSCOPE_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "wan2.5-t2i-preview", "input": { "prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display" }, "parameters": { "size": "1024*1024", "n": 1 }}'
Uma requisição bem-sucedida retorna um task_id. O ID é válido por 24 horas e não pode ser usado para consultas após expirar. Recupere o resultado prontamente.
Copy
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \ -H 'X-DashScope-Async: enable' \ -H "Authorization: Bearer $DASHSCOPE_API_KEY" \ -H 'Content-Type: application/json' \ -d '{ "model": "wan2.5-t2i-preview", "input": { "prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display" }, "parameters": { "size": "1024*1024", "n": 1 }}'{"request_id":"ca3b5224-bc60-4e47-80f4-2790040e9e55","output":{"task_id":"2de3f7e1-52ce-4cf4-a466-f2d318061c43","task_status":"PENDING"}}
Substitua {task_id} no comando abaixo pelo ID da tarefa obtido na Etapa 1, copie o comando para o terminal e execute-o.
A URL base a seguir refere-se à região Singapore. Use a URL base correspondente à sua região.
Copy
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Quando a tarefa for concluída (o task_status for SUCCEEDED), a resposta conterá uma URL de imagem. A URL da imagem é válida por 24 horas. Baixe-a prontamente.
Como o modelo leva muito tempo para processar (de dezenas de segundos a vários minutos), talvez seja necessário consultar esta API periodicamente. Recomendamos consultar a API a cada 3 a 5 segundos até que o task_status deixe de ser RUNNING .
Copy
curl -X GET https://dashscope.aliyuncs.com/api/v1/tasks/2de3f7e1-52ce-4cf4-a466-f2d3f8061c43 \--header "Authorization: Bearer $DASHSCOPE_API_KEY"{"request_id":"24143559-9964-4898-8f9c-d968bba182b9","output":{"task_id":"2de3f7e1-52ce-4cf4-a466-f2d3f8061c43","task_status":"SUCCEEDED","submit_time":"2025-12-03 10:19:18.293","scheduled_time":"2025-12-03 10:19:18.320","end_time":"2025-12-03 10:19:31.890","results":[{"orig_prompt":"A flower shop with exquisite windows, a beautiful wooden door, and flowers on display","actual_prompt":"A cozy, elegant flower shop. The exterior wall features exquisitely carved windows with dark brown wooden frames, and the glass is clean and bright, revealing the soft light inside. The front door is a beautiful solid wood door that retains its natural grain, complemented by a brass handle and a vintage nameplate that exudes a strong artisanal feel. On both sides of the front steps, and on the windowsills and entrance area, various flowers—including blooming roses, elegant hydrangeas, fresh daisies, and green eucalyptus leaves—are arranged in a staggered yet harmonious display. The background is a quiet European town streetscape, with a stone-paved road and a vine-covered neighboring wall enhancing the romantic atmosphere. The overall image is in a realistic photographic style, with soft, natural lighting that highlights the wood texture and floral details.","url":"https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1d/59/20251203/7a2bee47/2de3f7e1-52ce-4cf4-a466-f2d3f8061c43.png?Expires=1764814771&OSSAccessKeyId=YOUR_ACCESS_KEY_ID"}],"task_metrics":{"TOTAL":1,"FAILED":0,"SUCCEEDED":1}},"usage":{"image_count":1}}
Copy
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/8b108773-4e7d-4cd7-8c62-aad7a08d7769 \--header "Authorization: Bearer $DASHSCOPE_API_KEY"{"request_id":"0ee9ab8a-0ea4-9f0b-9cb0-41eaf24fd5e8","output":{"task_id":"8b108773-4e7d-4cd7-8c62-aad7a08d7769","task_status":"SUCCEEDED","submit_time":"2025-12-03 10:50:24.253","scheduled_time":"2025-12-03 10:50:24.282","end_time":"2025-12-03 10:50:42.708","results":[{"orig_prompt":"A flower shop with exquisite windows, a beautiful wooden door, and flowers on display","actual_prompt":"A warm and elegant flower shop, with an exterior wall decorated with an exquisitely carved window. The window frame is dark brown solid wood, with clean and bright glass revealing the soft light inside. The front door is a beautiful wooden door crafted with a vintage distressed technique, its surface retaining the wood grain texture, complemented by a brass door handle and a small nameplate decoration, exuding a strong handmade feel. In front of the door, on the windowsill, and on both sides of the entrance, various flowers are arranged in a staggered fashion—pink and white roses, pale purple hydrangeas, bright yellow sunflowers, and green eucalyptus leaves—with soft and layered colors. The background is a quiet European-style street, with cobblestones and vine-covered neighboring walls adding a romantic atmosphere. The overall image is in a realistic photography style, with warm and natural lighting, highlighting the tranquility and beauty of the flower shop.","url":"https://dashscope-result-sgp.oss-ap-southeast-1.aliyuncs.com/1d/63/20251203/c3a8f0e2/24817593-8b108773-4e7d-4cd7-8c62-aad7a08d7769.png?Expires=1748416642&OSSAccessKeyId=YOUR_ACCESS_KEY_ID"}],"task_metrics":{"TOTAL":1,"FAILED":0,"SUCCEEDED":1}},"usage":{"image_count":1}}%
Explore mais modelos: acesse o console do Model Studio para ver todos os modelos de imagem e vídeo suportados pelo Alibaba Cloud Model Studio (Bailian).