Camkode
Camkode

How to Create a Simple Web API with Flask

Posted by Kosal

How to Create a Simple Web API with Flask

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:

Step 1: Install Flask

If you haven't already installed Flask, you can do so using pip:

pip install Flask

Step 2: Create your Flask app

Create a Python script (e.g., flaskapi.py) and import Flask:

from flask import Flask

app = Flask(__name__)

Step 3: Define your API endpoints

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!'}

Step 4: Run the Flask app

At the end of your script, add the following code to run the Flask app:

if __name__ == '__main__':
    app.run(debug=True)

Step 5: Test your API

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.