0% found this document useful (0 votes)
37 views

Flask API To Fetch Data From MSSQL

This Python code defines a Flask API with two routes. The first route fetches all parts from a SQL database and returns them in JSON format. The second route looks up a single part by ID and returns the matching part details or an error message if not found. Both routes connect to a SQL database using Pymssql and return data or caught errors.

Uploaded by

Kememia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Flask API To Fetch Data From MSSQL

This Python code defines a Flask API with two routes. The first route fetches all parts from a SQL database and returns them in JSON format. The second route looks up a single part by ID and returns the matching part details or an error message if not found. Both routes connect to a SQL database using Pymssql and return data or caught errors.

Uploaded by

Kememia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

from flask import Flask, jsonify, request

import pymssql

app = Flask(__name__)

@app.route('/parts')

def get_parts():

try:

conn = pymssql.connect(server='10.0.1.11', user='start', password='sera', database='RPM_LIVE_V1')

cursor = conn.cursor()

cursor.execute('SELECT * FROM mainstores')

rows = cursor.fetchall()

parts = []

for row in rows:

part = {

'id': row[0],

'name': row[1],

'cost': row[2],

'stock': row[3],

'location': row[4],

'stock': row[5]

parts.append(part)

conn.close()

return jsonify(parts)
except Exception as e:

return str(e)

@app.route('/parts/<int:part_id>')

def get_part(part_id):

try:

conn = pymssql.connect(server=servername, user=user, password=**, database=db_name)

cursor = conn.cursor()

cursor.execute('SELECT * FROM mainstores WHERE id=%s', (part_id,))

row = cursor.fetchone()

if row:

part = {

'id': row[0],

'name': row[1],

'cost': row[2],

'stock': row[3],

'location': row[4],

'stock': row[5]

conn.close()

return jsonify(part)

else:

conn.close()

return jsonify({'error': 'Part not found'})

except Exception as e:
return str(e)

if __name__ == '__main__':

app.run(debug=True)

You might also like