flyio ip allocation using API

hello this is my code right now its allocating the IPs using cli but if not want to use cli is there an endpoint or any method to allocate ip using API here is my code

import requests
import os
import json
import time
import subprocess

# Environment variables
FLY_API_TOKEN = os.getenv('FLY_API_TOKEN')
FLY_API_HOSTNAME = 'https://api.machines.dev'
APP_NAME = 'streamlit-hello72'

headers = {
    'Authorization': f'Bearer {FLY_API_TOKEN}',
    'Content-Type': 'application/json'
}

def run_fly_command(command):
    """Execute a fly CLI command and return the output"""
    try:
        result = subprocess.run(
            command,
            check=True,
            text=True,
            capture_output=True
        )
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"Command failed with exit code {e.returncode}")
        print(f"Error output: {e.stderr}")
        return None

def create_app():
    """Create the application"""
    url = f"{FLY_API_HOSTNAME}/v1/apps"
    app_payload = {
        "app_name": APP_NAME,
        "org_slug": "personal"
    }
    
    try:
        response = requests.post(url, headers=headers, json=app_payload)
        response.raise_for_status()
        print("App created successfully!")
        return response.json()
    except requests.exceptions.RequestException as e:
        if hasattr(e, 'response') and e.response.status_code == 409:
            print("App already exists, continuing...")
        else:
            print(f"Error creating app: {e}")
            raise

def allocate_ips_with_cli():
    """Allocate IPs using fly CLI"""
    print("Allocating IPv4...")
    run_fly_command(['fly', 'ips', 'allocate-v4', '--shared', '-a', APP_NAME])
    
    print("Allocating IPv6...")
    run_fly_command(['fly', 'ips', 'allocate-v6', '-a', APP_NAME])
    
    # Show allocated IPs
    print("\nAllocated IPs:")
    run_fly_command(['fly', 'ips', 'list', '-a', APP_NAME])

def deploy_machine():
    """Deploy the machine with Streamlit"""
    url = f"{FLY_API_HOSTNAME}/v1/apps/{APP_NAME}/machines"
    
    machine_config = {
        "name": APP_NAME,
        "config": {
            "image": "registry.fly.io/muatafastreamlit-26:deployment-01JD20EHKQVH202XNMQP1SDB56@sha256:66fbb456314eddeaa297095130e347796a974e18654c7630a500dbfe578daa97",
            "env": {
                "PORT": "8505"
            },
            "services": [
                {
                    "ports": [
                        {
                            "port": 443,
                            "handlers": ["tls", "http"]
                        },
                        {
                            "port": 80,
                            "handlers": ["http"]
                        }
                    ],
                    "protocol": "tcp",
                    "internal_port": 8505
                }
            ],
            "guest": {
                "cpu_kind": "shared",
                "cpus": 2,
                "memory_mb": 512
            }
           
        }
    }

    try:
        response = requests.post(url, headers=headers, json=machine_config)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error deploying machine: {e}")
        if hasattr(e, 'response'):
            print(f"Response Status: {e.response.status_code}")
            print(f"Response Body: {e.response.text}")
        raise

def check_machine_status(machine_id):
    """Check the status of a machine"""
    url = f"{FLY_API_HOSTNAME}/v1/apps/{APP_NAME}/machines/{machine_id}"
    
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error checking machine status: {e}")
        return None

def main():
    try:
        # Create app
        create_app()
        
        # Allocate IPs using CLI
        print("Allocating IPs using CLI...")
        allocate_ips_with_cli()
        
        # Deploy machine
        print("Deploying machine...")
        machine_response = deploy_machine()
        machine_id = machine_response['id']
        print(f"Machine deployed with ID: {machine_id}")
        
        # Monitor deployment
        print("Monitoring deployment...")
        max_attempts = 20
        attempt = 0
        
        while attempt < max_attempts:
            status = check_machine_status(machine_id)
            if status:
                state = status.get('state', '')
                print(f"Current state: {state}")
                if state == 'started':
                    print("\nDeployment successful!")
                    print(f"Your app should be available at: https://{APP_NAME}.fly.dev")
                    
                    # Show final IP allocation using CLI
                    print("\nFinal IP allocation:")
                    run_fly_command(['fly', 'ips', 'list', '-a', APP_NAME])
                    break
            
            time.sleep(2)
            attempt += 1
        
        if attempt >= max_attempts:
            print("Deployment monitoring timed out")
            
    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":
    main()

We have a graphql endpoint for that. Here’s some old elixir code I used for my side projects, I hope this helps:

defmodule Fly.Machines do
  use Tesla

  plug(Tesla.Middleware.BaseUrl, "https://api.machines.dev/v1")
  plug(Tesla.Middleware.JSON)

  def create_app(client, org_slug, app_name) do
    post(client, "/apps", %{app_name: app_name, org_slug: org_slug})
  end

  def list_machines(client, app_name) do
    get(client, "/apps/#{app_name}/machines")
  end

  def create_machine(client, app_name, config) do
    post(client, "/apps/#{app_name}/machines", %{config: config})
  end

  def allocate_ip(client, app_name, type) do
    """
    mutation ($input: AllocateIPAddressInput!) {
      allocateIpAddress(input: $input) {
        ipAddress {
          address
        }
      }
    }
    """
    |> graphql_request(client, %{input: %{appId: app_name, type: type}})
  end

  def graphql_request(query, client, variables) do
    post(client, "https://api.fly.io/graphql", %{query: query, variables: variables})
  end

  def client(token) do
    middleware = [
      {Tesla.Middleware.Headers, [{"authorization", "Bearer " <> token}]}
    ]

    Tesla.client(middleware)
  end
end

You can get docs on that at GraphQL Playground

Its worth pointing that graphql is used in flyctl so, although its not gonna be suddenly removed/changed for the sake of compatibility, its not as customer-friendly as api.machines.dev

hey thanks i have wrote the python code it might be useful for someone trying

def graphql_request(query, variables):
    """Make a GraphQL request"""
    payload = {
        'query': query,
        'variables': variables
    }
    
    try:
        response = requests.post(FLY_GRAPHQL_API, headers=headers, json=payload)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"GraphQL request failed: {e}")
        if hasattr(e, 'response'):
            print(f"Response: {e.response.text}")
        raise

def allocate_ip(ip_type):
    """Allocate IP address using GraphQL"""
    query = """
    mutation ($input: AllocateIPAddressInput!) {
        allocateIpAddress(input: $input) {
            ipAddress {
                address
                type
            }
        }
    }
    """
    
    variables = {
        'input': {
            'appId': APP_NAME,
            'type': ip_type
        }
    }
    
    return graphql_request(query, variables)

def list_ips():
    """List IP addresses using GraphQL"""
    query = """
    query ($appId: String!) {
        app(id: $appId) {
            ipAddresses {
                nodes {
                    address
                    type
                }
            }
        }
    }
    """
    
    variables = {
        'appId': APP_NAME
    }
    
    return graphql_request(query, variables)

but the issues is its now showing
Shared v4 ip its just IP but from terminal if i allocate it its giving Shared v4
i dont know if this ip is a paid one or free one can you help me in this

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.