In this tutorial, we will be building a simple API using Python that will interact with a database using the GET method. We will be using the Flask framework to create the API and SQLite as our database.
Step 1: Setting up the environment
First, make sure you have Python installed on your machine. You can download Python from the official website if you don’t have it already. Next, install Flask by running the following command:
pip install Flask
Step 2: Create a new Python file for our API
Create a new Python file in your project directory and name it api.py
.
Step 3: Setting up the Flask app
In the api.py
file, import Flask and create a new Flask app instance:
from flask import Flask
app = Flask(__name__)
Step 4: Define the route for our API
Next, we will define a route that will return data from our database. For the sake of this tutorial, we will be using a simple SQLite database with a single table called users
. Here’s how you can define the route in the api.py
file:
import sqlite3
from flask import jsonify
@app.route('/users', methods=['GET'])
def get_users():
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
conn.close()
return jsonify(users)
Step 5: Running the Flask app
To run the Flask app, add the following code at the bottom of the api.py
file:
if __name__ == '__main__':
app.run(debug=True)
Run the app by executing the following command in your terminal:
python api.py
Step 6: Testing the API
You can now test the API by navigating to http://127.0.0.1:5000/users
in your web browser. This will return a JSON array of all the users in the database.
That’s it! You have successfully created a simple API using Python that interacts with a database using the GET method. You can extend this example by adding more routes and implementing other HTTP methods like POST, PUT, and DELETE.
I hope you found this tutorial helpful in learning how to create a GET API to a database using Python. Thank you for reading! #infysky #python