keepcalculator

06 Numbers and Powers

Check if a Local API Is Listening Before Calling It

Card No. 06·30244 · Updated · Standard formula, shown below

Calling a local API that isn’t up yet is a common source of errors in scripts and microservices. This guide shows you how to verify that an API endpoint is reachable and ready before you send your actual request, saving you from connection refused errors and confusing timeouts. You’ll learn several quick, practical methods using common command-line tools and simple code snippets.

What You’ll Need

  • A terminal or command prompt on the machine where the API runs (or can reach it over the network).
  • The API’s hostname (often localhost) and port number (e.g., 8080).
  • Basic familiarity with your operating system’s command line.
  • Optional: curl (pre-installed on macOS and most Linux; on Windows, it’s included with PowerShell or available via the Windows Store).

Step-by-Step

  1. Identify the exact address and port. Check your API’s configuration or documentation for the host and port it binds to. For local development, this is often http://localhost:3000 or http://127.0.0.1:5000. Make a note of the full base URL.
  2. Test the port with a simple connection tool. The quickest check is to see if something is listening on that port. On Linux/macOS, use nc -zv localhost 3000 (or nc -z -v). On Windows, you can use Test-NetConnection localhost -Port 3000 in PowerShell. A successful message like “Connection succeededâ€� means a service is there, but it doesn’t guarantee it’s your API.
  3. Send a lightweight HTTP request with curl. Use curl -I http://localhost:3000 to fetch only the headers. A response with an HTTP status code (e.g., 200 OK, 404 Not Found) means the server responded. If you get curl: (7) Failed to connect, nothing is listening on that port.
  4. Check the API’s health endpoint. Many APIs expose a dedicated health check route like /health or /ping. Try curl http://localhost:3000/health. A 200 response with a body like {"status":"ok"} is the most reliable sign the API is ready to accept requests.
  5. Use a script to wait for the API. In a shell script, you can loop until the port is open or the health endpoint returns success. For example, in Bash:
    while ! nc -z localhost 3000; do
      sleep 1
    done
    echo "API is up"
        

    Or with curl:

    until curl -s http://localhost:3000/health; do
      sleep 1
    done
        
  6. Integrate the check into your application code. If you’re calling the API from a program, add a pre-flight check. In Python, you might use socket.create_connection(("localhost", 3000), timeout=5) to test the port, or use a library like requests to hit the health endpoint with a short timeout and retry logic.
  7. Proceed with your actual API call. Once the check passes, make your real request. If you used a waiting loop, you can now safely call the API without worrying about connection errors.

Common Mistakes

  • Testing the wrong port. Double-check the port number in your API’s config. A typo (e.g., 3000 vs 3001) will cause a false negative.
  • Confusing “port openâ€� with “API ready.â€� A port can be open because another service is using it, or because the API is still starting up (e.g., loading a database). Always use a health endpoint if available.
  • Using ping to check a port. Ping uses ICMP, not TCP, so it only tells you if the host is reachable, not if a specific port is open.
  • Forgetting about firewalls or network namespaces. If the API runs in a container or a different machine, localhost may not be the right host. Use the container’s IP or the remote host’s address.
  • Not setting a timeout. Without a timeout, a check can hang indefinitely if the network is slow. Always specify a timeout (e.g., curl --max-time 5).

Tips

  • Use a health endpoint when possible. It’s the most accurate signal. If your API doesn’t have one, consider adding a simple route that returns 200 when the service is ready.
  • For production, use a proper orchestrator. In Kubernetes, use readiness probes. In Docker Compose, use depends_on with a healthcheck. These automate the waiting process.
  • In CI/CD pipelines, use a retry loop. Services can take a few seconds to start. A loop with a 1-second sleep and a max retry count is more robust than a single check.
  • Log the check result. When debugging, a clear log message like “API health check passedâ€� helps you trace issues.
  • Test from the same network context. If your API is on a VPN or a specific network interface, ensure your check is run from a machine that can reach it.

Troubleshooting

If your check fails, here’s what to do:

  • Connection refused: This almost always means nothing is listening on that port. Verify the API process is running (e.g., ps aux | grep node or check your IDE’s console). Check the port in the API’s configuration or startup logs.
  • Timeout: A timeout means the host is reachable but not responding. This could be due to a firewall, the API being overloaded, or it’s listening on a different interface (e.g., 127.0.0.1 vs 0.0.0.0). Try curl -v to see where it hangs.
  • 404 Not Found: The server is up, but the path you’re requesting doesn’t exist. Check the correct health endpoint path in your API’s docs.
  • 403 Forbidden: The API may require authentication or a specific header. Look at the API’s security settings.
  • Port is open but API doesn’t respond to HTTP: The service on that port might not be HTTP (e.g., a database). Confirm you’re hitting the right port.
  • Works from terminal but not from your app: Check if your app is running in a different environment (e.g., a container) that has different network settings. Use localhost vs host.docker.internal if needed.

Frequently Asked Questions

What’s the difference between checking a port and checking an HTTP endpoint?

Checking a port (e.g., with nc) only tells you if a TCP connection can be established. Checking an HTTP endpoint (e.g., with curl) tells you if an HTTP server is actually responding. The latter is more reliable for API readiness.

Can I use ping to check if an API is listening?

No. ping uses ICMP, which is a different protocol. It only confirms the host is up, not that any specific port is open.

How long should I wait before giving up?

It depends on your API’s startup time. For a typical local dev server, 5-10 seconds is usually enough. For heavier services (e.g., with database connections), you might wait 30 seconds or more. Use a retry loop with a max attempt count.

What does “Connection refused� mean exactly?

It means the TCP handshake was rejected because no process is listening on that port. This is a definitive sign that the API is not running (or not bound to that port).

Is it okay to just call the API and catch the error?

Sometimes, but it’s not ideal. If the API is slow to start, you might get a connection error that you have to handle. A pre-check makes your code cleaner and avoids unnecessary error-handling complexity.

Do I need to check before every call?

No, only when the API might not be up yet, such as during startup or after a restart. Once you know it’s up, subsequent calls should work fine unless the API crashes.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →