Introduction
In this article, you will learn how to create REST API to read Microsoft SQL table and export the result to CSV file using Python. I have created a simple Microsoft SQL table for this demo named as Employees which contains the following columns and rows.
![]()
Topics Covered
This article demonstrates how to build the following:
- Create the project folder
- Install the required packages
- Implement the REST API
- Test the API
Prerequisites
- Windows machine and Visual Studio code are used for this article. Complete all the prerequisites mentioned in this article.
- Install the Microsoft ODBC Driver for SQL Server on Windows.
Tools
- Visual Studio Code
Task 1: Create the project folder
In this task, you will see how to create the project folder.
Step 1
Open Windows Command Prompt and run the following commands to create the new folder for this project.
Task 2: Install the required packages
In this task, you will see how to install the required packages for this project.
Step 1
Open ExportDataCSV folder in Visual Studio Code. Click Terminal -> New Terminal.
Step 2
Run the following command to install the packages required for this project.
- flask is a simple framework for building complex web applications.
- flask-restful is an extension for Flask that adds support for quickly building REST APIs
- pyodbc is an open source Python module that makes accessing ODBC databases simple.
- pandas provides fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive.
Task 3: Implement the REST API
In this task, you will see how to implement the REST API to read the Microsoft SQL table and export the results to CSV file.
Step 1
In Visual Studio Code, create a new file app.py under ExportDataCSV folder. Note: Update the connection string value.
Step 2
Copy and paste the below code.
Task 3: Test the API
In this task, you will see how to test the API which creates the CSV file with data read from Microsoft SQL table.
Step 1
In Visual Studio Code, run the following command in the Terminal.
Step 2
Open the browser and access the below URL. CSV file gets created in ExportDataCSV folder as shown below.
![]()
References
- Flask-RESTful documentation
- Python SQL Driver - pyodbc
- pandas.DataFrame.to_csv
Summary
This article describes how to read Microsoft SQL table and export the result to CSV file using Python.