Drawing Parallels between .Net and Python using rest API creation

Drawing Parallels between .Net and Python using rest API creation

Are you familiar with how REST APIs are created in .NET and curious about replicating the process in Python? Or perhaps you're simply eager to dive into basic Python commands?

If your answer is yes, you've come to the right place.

In this article, we'll explore how to create basic CRUD endpoints in Python.


Background Information:

When we create a WebAPI project in Visual Studio, it provides us with a template that includes a "WeatherForecastController." This controller contains CRUD (Create, Read, Update, Delete) endpoints with hardcoded data, serving as a foundation to develop custom APIs. In this article, we aim to replicate these endpoints using Python


Python Environment Setup:

  1. Download and install Python from https://www.python.org/downloads/. If you're using Windows OS, make sure to check the option 'Add Python to environment variables' during installation.
  2. Next, we need to install Flask. Flask is a web framework for Python, comparable to ASP.NET Core, specifically ASP.NET Core MVC.


Now, let's create a Python file and write some code:

  1. Create a directory or folder where you want to store your code.
  2. It's recommended to use a code editor for better file management. I'll be using Visual Studio Code.
  3. Create a file to hold the code for CRUD endpoints. Name it 'weatherEndpoints.py' (you can use any name you prefer).
  4. Copy and paste the following code into the file. You'll find line comments to help you understand the syntax:"


from flask import Flask, jsonify, request  # This is using statement in C#

app = Flask(__name__)  # Here we define a flask app which we will run at the end

forecasts = [
    {"Id": 1, "Date": "2024-04-22", "TemperatureC": 25, "Summary": "Sunny"},
    {"Id": 2, "Date": "2024-04-23", "TemperatureC": 18, "Summary": "Cloudy"}
] # this is how we define list in python

@app.route('/weatherforecast', methods=['GET'])  # routing similar to attribute routing in .net
def get_forecasts(): # in python we define methods by using def
    return jsonify(forecasts)

@app.route('/weatherforecast/<int:id>', methods=['GET'])
def get_forecast(id):
    forecast = next((f for f in forecasts if f["Id"] == id), None)
    if forecast:
        return jsonify(forecast)
    else:
        return jsonify({"error": "Forecast not found"}), 404

@app.route('/weatherforecast', methods=['POST'])
def create_forecast():
    data = request.get_json()
    data["Id"] = len(forecasts) + 1
    forecasts.append(data)
    return jsonify(data), 201

@app.route('/weatherforecast/<int:id>', methods=['PUT'])
def update_forecast(id):
    forecast = next((f for f in forecasts if f["Id"] == id), None)
    if forecast:
        data = request.get_json()
        forecast.update(data)
        return jsonify(forecast)
    else:
        return jsonify({"error": "Forecast not found"}), 404

@app.route('/weatherforecast/<int:id>', methods=['DELETE'])
def delete_forecast(id):
    forecast = next((f for f in forecasts if f["Id"] == id), None)
    if forecast:
        forecasts.remove(forecast)
        return '', 204
    else:
        return jsonify({"error": "Forecast not found"}), 404

if __name__ == '__main__':
    app.run(debug=True)  #This starts the flask app which we defined in the beginning in debug mode
# __name__ is a built-in variable and represents the name of the current module.
# When we run python file, Python sets the __name__ variable  '__main__'.        

To run the above code:

  1. Open a terminal or command prompt in the same directory where your 'weatherEndpoints.py' file is located.
  2. Execute the following command:

         python weatherEndpoints.py        

This will start the Flask server, and you should see messages indicating that the endpoints are now being served. Refer to the screenshot below:


Article content

To see the endpoints in action:

  1. Open any HTTP client, such as a browser or Postman.
  2. Hit the endpoints we defined in the code. For example:

GET endpoint: http://localhost:5000/weatherforecast or http://127.0.0.1:5000/weatherforecast

From here, you can interact with the endpoints and test their functionality.

Note: Flask, by default, runs its development server on port 5000. This can be changed by providing the --port option when running the Flask app.


By following these steps, you can successfully set up and run basic CRUD endpoints in Python using Flask. Whether you're new to Python or looking to expand your web development skills, Flask provides a versatile framework for building powerful APIs. Happy coding!

To view or add a comment, sign in

Explore content categories