Creating the backend API in C#

As we move ahead, there are times when as a developer we not only need to consume APIs, but create our own APIs for others to use. Even if we find recurring usage of some functions, keeping in mind web framework strategy, we need to ensure that instead of simply creating functions for that task, we need to convert them to APIs. A big advantage of that is that the usage of our function or task will then not be limited only to Python, but it can be used in any scripting language or web language.

Here we will see a very basic approach to creating a functional API to say Hello World in C#. As a prerequisite, we will need IIS to run the web services, and Visual Studio (Community edition is free to use) to create our own API. Later on, we will see how to consume that API in Python.

Additionally, we will ensure that the return value is in the JSON format, which is the industry standard for API communication, replacing XML.

  1. Invoke the C# Web project in Visual Studio:
  1. Select the Web API checkbox in the next screen shown as follows:
  1. Add the Controller (this is the main component that will ensure the API framework is active):
  1. Give a meaningful name to the controller. Note, the name must be followed by the word Controller (example testController), otherwise the controller will not function and the API framework will be broken:
  1. Once the controller is added, under the WebApiConfig.cs file add the new JsonMediaTypeFormatter() config, as shown in the next screenshot. This ensures that every output returned from the API will be in JSON format:
  1. In the main apitestController.cs program, return the value Hello World once the Get method is called:
  1. Once done, click on the Run button that is available in the Visual Studio application. A screen similar to the following screenshot will be opened, which ensures that the local IIS server is being invoked and the application is initialized for testing:
  1. Once the application is loaded, a URL similar to the following will confirm our API is working fine. Note that, at this point, the local IIS Express is being used and the API is still not published for external use:
  1. Once validated, now we need to publish this to our IIS. Similar to what we did earlier, we create a new application in IIS (named apitest in our case):
  1. Once the IIS mapping has been done, we use Visual Studio to publish our API project to this web folder:
  1. We create a web Publish profile, and publish it to the local folder that we mapped to our IIS:
  1. Our API is ready to be used. We can validate it by going to http://localhost on our browser:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.197.26