Skip to main content
Clientes e Ferramentas de Desenvolvedor

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.

Mecanismo de chamada assíncrona

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:
  1. Crie uma tarefa: chame a API para criar uma tarefa. O service retorna sincronamente um ID de tarefa (task_id).
  2. 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.
Exemplo de chamada HTTP (texto para imagem)
image

Método 1: Usar o Postman (recomendado)

Ao converter um comando cURL para uma requisição no Postman, os parâmetros são mapeados da seguinte forma:

Parâmetro do cURL

Interface do Postman

Descrição

curl -X POST ou curl -X GET

Menu suspenso de método de requisição

Seleciona o método de requisição HTTP.

https://<api-endpoint-url>

Caixa de entrada de URL

A URL do endpoint da API.

-H 'Key: Value'

Aba Headers

Configure os cabeçalhos da requisição como pares chave-valor.

-d '{...}'

Aba Body

Configure o corpo da requisição.

Pré-requisitos

Antes de chamar a API, obtenha uma chave de API para sua região e baixe o Postman.

Etapa 1: Crie uma tarefa

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.
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
    }
}'
  1. No Postman, clique em no botão new ou + para crie uma nova requisição e selecione HTTP como tipo de requisição.
  2. 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.
POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
  1. 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.

  2. 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.
{
    "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.
  1. 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.
{
    "request_id": "896b2ccd-a0cd-40a8-a557-bb73cee5cf95",
    "output": {
        "task_id": "42442de9-917d-4c41-80a7-37fb7ad25ed2",
        "task_status": "PENDING"
    }
}

Etapa 2: Consultar resultado pelo ID da tarefa

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
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
  1. Configure a requisição de consulta no Postman:
    1. Crie uma nova requisição HTTP.
    2. Defina o método de requisição como GET.
    3. 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.
    4. Na aba Headers, adicione o cabeçalho Authorization, utilizando a mesma chave de API da Etapa 1.
    5. Clique em em Send.
GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/42442de9-917d-4c41-80a7-37fb7ad25ed2

Headers:
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.1
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Authorization: Bearer sk-xxx
  1. 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.
"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"
            }
        ]

Método 2: Usar o cURL

Desenvolvedores familiarizados com a linha de comando podem usar o cURL para testar a API rapidamente.

Pré-requisitos

Antes de execute o comando cURL:
  • Ative o service de modelo e obtenha uma chave de API.
  • 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.
    Execute o seguinte comando para verificar se o cURL está instalado.
    curl --version
    
    Se você vir uma saída semelhante à seguinte, o cURL está instalado:
    curl 8.x.x (x86_64-apple-darwin23.0) libcurl/8.x.x (SecureTransport) LibreSSL/3.3.6 zlib/1.2.12 nghttp2/1.58.0
    Release-Date: 2023-10-11
    Protocols: dict file ftp ftps gopher gophers http https imap imaps ldap ldaps mqtt pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
    Features: alt-svc AsynchDNS GSS-API HSTS HTTP2 HTTPS-proxy IPv6 Kerberos Largefile libz MultiSSL NTLM NTLM_WB SPNEGO SSL threadsafe UnixSockets
    
    Caso não esteja instalado, você poderá ver uma mensagem como uma das seguintes:
    • Windows: 'curl' is not recognized as an internal or external command, operable program or batch file.
    • Linux/macOS: command not found: curl.
    Acesse a página de download do curl para instalá-lo.

Etapa 1: Crie uma tarefa

  • Execute o seguinte comando no seu terminal:
    A URL base a seguir refere-se à região Singapore. Use a URL base correspondente à sua região.
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.
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"}}

Etapa 2: Consultar resultado pelo ID da tarefa

  • 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.
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 .
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}}
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}}%

Próximas etapas

Após gerar sua primeira imagem com sucesso, explore os seguintes recursos:
  • Saiba mais sobre os parâmetros da API: consulte a documentação da API text-to-image para conhecer parâmetros adicionais.
  • Experimente a geração de vídeo: teste a API first-frame-to-video para crie um vídeo.
  • 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).
Plano de Tokens
Playground de Modelos
  • Music generation
Inferência do Modelo
Avaliação
Compressão de Modelos
Estatísticas e Monitoramento
Suporte