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:
Now, let's create a Python file and write some code:
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:
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:
To see the endpoints in action:
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!