Question How to check whether Rest API is up or down

raysefo

Well-known member
Joined
Feb 22, 2019
Messages
362
Programming Experience
10+
A web API doesn't put a sign out to say whether it is running or not. You need to contact it and see whether you get the expected reply. It would have to be running in order to tell you that it's not running any other way. Pinging it is the most basic way to contact a server and get a reply.
 
I use a web api method for my test system that hits the method every period of time checking for a result to be returned. I have a .NET solution that tests various WCF services and Web API's every 5 minutes. I use a product called IPSentry for my servers that test services and can also make web requests.
 
In regards to what JM said. That would be the most effective way to test a connection to a server.

Think about it. How can you connect to a servers API, if the server is down? So wouldn't it make more sense to use something like the ping class, or CMD as a shell which can be executed silently to ping a server for a response?

You can read mine and @Skydiver 's multiple variations of code and detailed discussion of how you can do this on the following thread : Can't Keep Cmd From Opening When My GUI Pings - C# | Dream.In.Code
 
Also, I highly recommend actually trying to access the WebAPI to try to determine if it is up or down. Ping is not sufficient. A machine hosting a web server maybe up and running and responding to pings, but the web server (be it IIS, Apache, node.js, Tomcat, JBoss, etc.) may not be running.
 
Thank you @Skydiver . Here is how I check one of the 3rd party API. I will just add send e-mail mechanism if it gets an error while calling the API.

C#:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace TestGameProduct
{
    internal class Program
    {
        private static readonly HttpClient httpc = new HttpClient();

        static async Task Main(string[] args)
        {
            FormUrlEncodedContent content = null;

            var productsDto = new ProductRequestDto();

            var applicationCode = "52e7cf9abc";
            var secretKey = "e560111000101";
            var version = "V1";
            string source = applicationCode + version + secretKey;

            using (var md5Hash = MD5.Create())
            {
                var hash = GetMd5Hash(md5Hash, source);
                productsDto.signature = hash;
                productsDto.ApplicationCode = applicationCode;
                productsDto.version = version;
            }

            //Convert request
            var keyValues = productsDto.ToKeyValues();
            content = new FormUrlEncodedContent(keyValues);

            await RunWithoutUsingHttpClient(content);
        }

        
        private static async Task RunWithoutUsingHttpClient(FormUrlEncodedContent content)
        {
            httpc.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Basic", "QklNOlFqSjQ1R1");
            
            for (int x = 0; x < 5000; x++)
            {
                HttpResponseMessage message = await httpc.PostAsync("http://test.com/test/Product/", content);
                Console.WriteLine(message.StatusCode);
            }
            Console.WriteLine("Connections Established");
            Console.ReadLine();
        }

        
        public static string GetMd5Hash(HashAlgorithm md5Hash, string input)
        {
            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }


    }

    public static class ObjectExtension
    {
        public static IDictionary<string, string> ToKeyValues(this object metaToken)
        {
            if (metaToken == null)
            {
                return null;
            }

            JToken token = metaToken as JToken;
            if (token == null)
            {
                return ToKeyValues(JObject.FromObject(metaToken));
            }

            if (token.HasValues)
            {
                var contentData = new Dictionary<string, string>();

                foreach (var child in token.Children().ToList())
                {
                    var childContent = child.ToKeyValues();
                    if (childContent != null)
                    {
                        contentData = contentData.Concat(childContent).ToDictionary(k => k.Key, v => v.Value);
                    }
                }

                return contentData;
            }

            var jValue = token as JValue;
            if (jValue?.Value == null)
            {
                return null;
            }

            var value = jValue?.Type == JTokenType.Date
                ? jValue?.ToString("o", CultureInfo.InvariantCulture)
                : jValue?.ToString(CultureInfo.InvariantCulture);

            return new Dictionary<string, string> { { token.Path, value } };
        }
    }
    public class ProductRequestDto
    {
        public string version { get; set; }
        public string signature { get; set; }
        public string ApplicationCode { get; set; }
    }


}
 
I highly recommend actually trying to access the WebAPI to try to determine if it is up or down. Ping is not sufficient.
I would disagree. How can you access the API if the server isn't responsive? If a server is not responding to pings, its not going to respond to API calls. Pinging the server when the API isn't responsive would be the first step. Clearly if it pings, you may need to restart the service that your API depends on. To say that ping is not sufficient is not only an understatement, but condescending to those of us who have been working with networks for the better half of our lives. How can you access the API to check if the server isn't responsive to incoming connections? You're entitled to your opinion, i guess.
 
It's one thing for the IIS web site to reply to a ping, it's another to check that your publish and compile worked and the application is answering.
 
And on that note; there is no way to determine if the API is operating or not if the server isn't responding to incoming requests. A ping would be the first of a series of tests to run.

If you realize the API is not responding. Pinging your server and getting a 200 response will indicate that your problem is with your API and it may be time to restart some services, or check your load balancing settings.

You're looking for a response 200 Action Results in Web API 2 - ASP.NET 4.x => Look at the interface

You can also find statuses here : HTTP/1.1: Status Code Definitions
 
I thought that when you were saying "ping" you were talking about ICMP ping. This is the ping that I was talking about as being insufficient.

Based on your response on post #11, it seems that your "ping" is actually an HTTP request. (I've never heard of an ICMP ping give a 200 response.) This is what I meant by actually calling the WebAPI. You want to get a response back from the actual web service that you are calling, not just an ICMP ping response from the server hosting the web service.
 
I thought that when you were saying "ping" you were talking about ICMP ping.
I was. This would be the last method I would execute, after making a http get request. If the API is not responsive, then, you need to be certain that your API is certainly the problem and you do that by pinging the server hosting the API with the method you used linked above. If your server responds respectively to pings, then its safe to assume that your server may have issues with load balancing or something else which is causing it to not respond. That is why I said :
A ping would be the first of a series of tests to run.
...to elaborate... after a http request be made. I still think ping is a worthy way of distinguishing where a problem remains in a situation like that.
on post #11, it seems that your "ping" is actually an HTTP request.
No, I am sorry you misread it like that. I probably should have put more effort into explaining what I meant, but my head is all muzzy from all the long hours at Youtube, as well as my main job, and personal contracts, I'm not getting a lot of sleep these days. Nevertheless, I thought those reading this would have known what i meant, as its only common sense to check the IP of the server if you can't get a response from your web servers API. Now that I've explained that better, I still stand by what I said.
 

Latest posts

Back
Top Bottom