Article
· 22 hr il y a 6m de lecture

Écriture d'un service API REST pour exporter les données patient générées au format .csv

Salut,

C'est moi encore 😁. Je travaille actuellement à la génération de fausses données patients à des fins de test avec Chat-GPT et Python. J'aimerais également partager mon apprentissage. 😑

Tout d'abord, créer un service d'API REST personnalisé est facile en utilisant %CSP.REST.

Commençons ! 😂

1. Créez une classe datagen.restservice qui étend %CSP.REST.

Class datagen.restservice Extends %CSP.REST
{
Parameter CONTENTTYPE = "application/json";
}

2. Ajoutez une fonction genpatientcsv() pour générer les données du patient et les regrouper dans une chaîne csv

Class datagen.restservice Extends %CSP.REST
{
Parameter CONTENTTYPE = "application/json";
ClassMethod genpatientcsv() As %String [ Language = python ]
{
    # w ##class(datagen.restservice).genpatientcsv()
    # python.exe -m pip install faker
    # python.exe -m pip install pandas

    from faker import Faker
    import random
    import pandas as pd
    from io import StringIO

    # Initialize Faker
    fake = Faker()

    def generate_patient(patient_id):
        return {
            "PatientID": patient_id,
            "Name": fake.name(),
            "Gender": random.choice(["Male", "Female"]),
            "DOB": fake.date_of_birth(minimum_age=0, maximum_age=100).strftime("%Y-%m-%d"),
            "City": fake.city(),
            "Phone": fake.phone_number(),
            "Email": fake.email(),
            "BloodType": random.choice(["A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"]),
            "Diagnosis": random.choice(["Hypertension", "Diabetes", "Asthma", "Healthy", "Flu"]),
            "Height_cm": round(random.uniform(140, 200), 1),
            "Weight_kg": round(random.uniform(40, 120), 1),
        }

    # Generate 10 patients
    patients = [generate_patient(i) for i in range(1, 11)]

    # Convert to DataFrame
    df = pd.DataFrame(patients)

    # Convert to CSV string (without saving to file)
    csv_buffer = StringIO()
    df.to_csv(csv_buffer, index=False)
    csv_string = csv_buffer.getvalue()

    return csv_string
}
}

vous pouvez tester la fonction dans le terminal en tapant

w ##class(datagen.restservice).genpatientcsv()

3. Ajoutez une fonction GetMyDataCSV() en Python pour renseigner la chaîne CSV sous forme de fichier CSV, puis l'afficher via l'API REST. Pour ce faire, procédez comme suit :

3.1. Appelez la fonction de génération de données patient pour obtenir la chaîne CSV ;
3.2. Définissez %response.ContentType = "text/csv" ;
3.3. Définissez la valeur de l'en-tête « Content-Disposition » sur « attachment; filename=mydata.csv » ;
3.4. Écrivez la chaîne CSV générée en sortie.

N'oubliez pas d'installer les bibliothèques associées via PIP.

Class datagen.restservice Extends %CSP.REST
{
Parameter CONTENTTYPE = "application/json";
ClassMethod GetMyDataCSV() As %Status
{
    // Build CSV string
    Set tCSVString = ##class(datagen.restservice).genpatientcsv()

    //Set headers and output CSV
    Set %response.ContentType = "text/csv"
    Do %response.SetHeader("Content-Disposition","attachment; filename=mydata.csv")
    
    // Output the data
    W tCSVString

    Quit $$$OK
}

ClassMethod genpatientcsv() As %String [ Language = python ]
{
    # w ##class(datagen.restservice).genpatientcsv()
    # python.exe -m pip install faker
    # python.exe -m pip install pandas

    from faker import Faker
    import random
    import pandas as pd
    from io import StringIO

    # Initialize Faker
    fake = Faker()

    def generate_patient(patient_id):
        return {
            "PatientID": patient_id,
            "Name": fake.name(),
            "Gender": random.choice(["Male", "Female"]),
            "DOB": fake.date_of_birth(minimum_age=0, maximum_age=100).strftime("%Y-%m-%d"),
            "City": fake.city(),
            "Phone": fake.phone_number(),
            "Email": fake.email(),
            "BloodType": random.choice(["A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"]),
            "Diagnosis": random.choice(["Hypertension", "Diabetes", "Asthma", "Healthy", "Flu"]),
            "Height_cm": round(random.uniform(140, 200), 1),
            "Weight_kg": round(random.uniform(40, 120), 1),
        }

    # Generate 10 patients
    patients = [generate_patient(i) for i in range(1, 11)]

    # Convert to DataFrame
    df = pd.DataFrame(patients)

    # Convert to CSV string (without saving to file)
    csv_buffer = StringIO()
    df.to_csv(csv_buffer, index=False)
    csv_string = csv_buffer.getvalue()

    return csv_string
}
}

4. Ajoutez la route à cette fonction et compilez la classe

Class datagen.restservice Extends %CSP.REST
{
Parameter CONTENTTYPE = "application/json";
XData UrlMap [ XMLNamespace = "http://www.intersystems.com/urlmap" ]
{
<Routes>
        <Route Url="/export/patientdata" Method="GET" Call="GetMyDataCSV"/>
</Routes>
}

ClassMethod GetMyDataCSV() As %Status
{
    // Build CSV string
    Set tCSVString = ##class(datagen.restservice).genpatientcsv()

    //Set headers and output CSV
    Set %response.ContentType = "text/csv"
    Do %response.SetHeader("Content-Disposition","attachment; filename=mydata.csv")
    
    // Output the data
    W tCSVString

    Quit $$$OK
}

ClassMethod genpatientcsv() As %String [ Language = python ]
{
    # w ##class(datagen.restservice).genpatientcsv()
    # python.exe -m pip install faker
    # python.exe -m pip install pandas

    from faker import Faker
    import random
    import pandas as pd
    from io import StringIO

    # Initialize Faker
    fake = Faker()

    def generate_patient(patient_id):
        return {
            "PatientID": patient_id,
            "Name": fake.name(),
            "Gender": random.choice(["Male", "Female"]),
            "DOB": fake.date_of_birth(minimum_age=0, maximum_age=100).strftime("%Y-%m-%d"),
            "City": fake.city(),
            "Phone": fake.phone_number(),
            "Email": fake.email(),
            "BloodType": random.choice(["A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"]),
            "Diagnosis": random.choice(["Hypertension", "Diabetes", "Asthma", "Healthy", "Flu"]),
            "Height_cm": round(random.uniform(140, 200), 1),
            "Weight_kg": round(random.uniform(40, 120), 1),
        }

    # Generate 10 patients
    patients = [generate_patient(i) for i in range(1, 11)]

    # Convert to DataFrame
    df = pd.DataFrame(patients)

    # Convert to CSV string (without saving to file)
    csv_buffer = StringIO()
    df.to_csv(csv_buffer, index=False)
    csv_string = csv_buffer.getvalue()

    return csv_string
}
}

OK, maintenant notre code est prêt. 😁 La prochaine étape consiste à ajouter le service REST à l'application Web

Saisissez Path, Namespace, et Rest service class name, puis enregistrez

Attribuez le rôle d'application approprié à cette application Web (parce que je suis paresseux, j'attribue simplement %All pour les tests 🤐)

OK, tout est prêt ! 😁 Testons l'API REST ! 😂

Saisissez le chemin suivant dans un navigateur.

http://localhost/irishealth/csp/mpapp/export/patientdata

Cela déclenche le téléchargement d'un fichier nommé mydata.csv 😗

Vérifions le fichier 😊

Ouais ! Ça marche bien ! 😁😁

Merci beaucoup pour votre lecture. 😉

Discussion (0)1
Connectez-vous ou inscrivez-vous pour continuer