Tujamo
Tujamo

Reputation: 103

How to retrieve data from an API and load to Azure SQL database in Azure Functions in Python?

I'm really just looking for a short Python example using Azure functions that pulls in some data from an API (any) pushes it to an Azure SQL database based on a timer trigger.

Any resources or examples would be highly appreciated!

Upvotes: 1

Views: 1132

Answers (1)

Stanley Gong
Stanley Gong

Reputation: 12153

This is a simple python Azure function demo code for you,I created a table named demotable with only 2 colms : id(primary key,auto increment) and content(varchar,used for saving API response).

This is my code :

import logging
import azure.functions as func
import requests
import pyodbc

SQLConnStr = '<your sql conntion string>'

def main(mytimer: func.TimerRequest) -> None:
    result = requests.get("https://google.com")    
    print(result.status_code)

    conn = pyodbc.connect(SQLConnStr)
    cursor = conn.cursor()
    cursor.execute("insert into demotable values ('"+str(result.status_code)+"')")
    cursor.commit()
    conn.close()
    

requirement.txt:

azure-functions
requests
pyodbc
    

Each time this function will access google and save the response status code into SQL.

Result:

enter image description here

For how to use VS code to develop an Azure python function, see here.

And make sure that you have enabled the Azure SQL firewall for your Azure function before you access it. Details see here.

Let me know if you have any further questions.

Upvotes: 1

Related Questions