Python Web Client Retrieving Factorial Calculations from ASP.NET Core Website

When I wrote the ASP.NET Core Website that calculates the factorial of a number I promised myself I would write a Python client that uses the factorial service. After a minor change to the website to handle custom http headers, I wrote a quick Python client using the Requests http library for Python. Here are the details.

Custom Headers and ASP.NET Core

The ASP.NET Core Website that calculates a factorial returns results like this when running in a browser.

ASP.NET Core Routing Tutorial Calculating a Factorial

This is fine for viewing in a browser, but for api-like clients it is better to just return the number without the formatting. Therefore, I made a minor change to factorialRequestHandler to look for a custom http header from my Python client and emit only the factorial for those requests. Here is the new code for Startup.

public class Startup {
        public void ConfigureServices(IServiceCollection services) {
            services.AddRouting();
        }

        public void Configure(IApplicationBuilder app) {

            var rb = new RouteBuilder(app);

            RequestDelegate factorialRequestHandler = c => {
                var number = c.GetRouteValue("number") as string;

                int value;
                if (Int32.TryParse(number, out value)) {
                    value = Math.Abs(value);
                    var results = Factorial.Calculate(value);

                    var response = $"{number}! = {results}";

                    if (c.Request.Headers.ContainsKey("user-agent")
                    && c.Request.Headers["user-agent"].Equals("python-app"))
                        response = results.ToString();

                    return c.Response.WriteAsync(response);
                }

                return c.Response.WriteAsync("${number} is not an integer.");
            };

            rb.MapGet("factorial/{number:int}", factorialRequestHandler);

            var routes = rb.Build();

            app.UseRouter(routes);
        }
    }

If the user-agent in the http headers is set to "python-app", the service just returns the factorial and not the formatted string.

To be clear, in a browser without the custom http header, the factorial service will return:

15! = 1307674368000

When using the Python web client with the custom http header it will return:

1307674368000

Python Web Client using Requests Library

Now comes the easy part- creating a Python web client to list the factorials for numbers 1 through 10.

I really like the Requests http library for Python so I install it using pip:

pip install requests

Now I write a simple Python script that calls the factorial service of the ASP.NET Core Website to calculate the factorial for numbers 1 - 10. Here is the code.

import requests

headers = {'user-agent': 'python-app'}

for i in range(1, 11):
    r = requests.get('http://localhost:5000/factorial/' + str(i), headers=headers)
    print '{:2}! = {}'.format(i, r.text)

Here is the output.

 1! = 1
 2! = 2
 3! = 6
 4! = 24
 5! = 120
 6! = 720
 7! = 5040
 8! = 40320
 9! = 362880
10! = 3628800

Perfect:)

Conclusion

I absolutely love learning both Python and ASP.NET Core at the same time, and I hope using the combination in this article is interesting to both Python and ASP.NET Core enthusiasts. In addition to a bunch of other tutorials, I know I want to write the service using Flask as well as using ASP.NET Core Web API. Thank you for reading!

P.S. My online cryptography class starts today!

Posted by David Hayden
Koder Dojo
David Hayden is a professional Microsoft web developer. He mentors and tutors computer science students in C, C++, Java, and Python. In addition to writing computer science and programming tutorials at Koder Dojo, he also writes tutorials on C#, ASP.NET Core, and Azure as well as tutorials on Orchard Core.