Posted by Kosal
Creating a simple Web API with Flask is straightforward. Flask is a lightweight web framework for Python, making it ideal for building APIs quickly. Below are the steps to create a simple Web API with Flask:
If you haven't already installed Flask, you can do so using pip:
pip install Flask
Create a Python script (e.g., flaskapi.py
) and import Flask:
from flask import Flask
app = Flask(__name__)
You can define routes for different API endpoints using Flask's @app.route
decorator. Below is an example of defining a simple endpoint that returns a JSON response:
@app.route('/api/hello')
def hello():
return {'message': 'Hello, World!'}
At the end of your script, add the following code to run the Flask app:
if __name__ == '__main__':
app.run(debug=True)
Save the changes to flaskapi.py
and run it:
flask --app flaskapi run
Your Flask app should now be running locally. You can test your API by sending requests to http://127.0.0.1:5000/api/hello
using tools like curl, Postman, or your web browser. You should see a JSON response {"message": "Hello, World!"}
.
That's it! You've created a simple Web API with Flask. From here, you can expand your API by adding more endpoints, handling request parameters, integrating with databases, implementing authentication, etc., based on your requirements.