0

I have created a simple API with FastAPI and I want to export the output in a text file (txt).

This is a simplified code

import sys
from clases.sequence import Sequence
from clases.read_file import Read_file
from fastapi import FastAPI
 
app = FastAPI()
 
@app.get("/DNA_toolkit")
def sum(input: str):                        # pass the sequence in, this time as a query param
    DNA = Sequence(input)                         # get the result (i.e., 4)
    return {"Length": DNA.length(),         # return the response
            "Reverse": DNA.reverse(),
            "complement":DNA.complement(),
            "Reverse and complement": DNA.reverse_and_complement(),
            "gc_percentage": DNA.gc_percentage()
            } 


And this is the output

{"Length":36,"Reverse":"TTTTTTTTTTGGGGGGGAAAAAAAAAAAAAAAATAT","complement":"ATATTTTTTTTTTTTTTTTCCCCCCCAAAAAAAAAA","Reverse and complement":"AAAAAAAAAACCCCCCCTTTTTTTTTTTTTTTTATA","gc_percentage":5.142857142857143}

The file I would like to get

Length 36
Reverse TTTTTTTTTTGGGGGGGAAAAAAAAAAAAAAAATAT
complement ATATTTTTTTTTTTTTTTTCCCCCCCAAAAAAAAAA
Reverse and complement AAAAAAAAAACCCCCCCTTTTTTTTTTTTTTTTATA

There is a simple way to do this. This is my first time working with APIs and I don't even know how possible is this

  • Welcome to Stack Overflow! You seem to be asking for someone to write some code for you. Stack Overflow is a question and answer site, not a code-writing service. Please [see here](http://stackoverflow.com/help/how-to-ask) to learn how to write effective questions. – Blackgaurd Nov 10 '21 at 16:06
  • huh he has provided the code though. Question can be summarized how do i write a dictionary to a file. Here are some options https://stackoverflow.com/questions/36965507/writing-a-dictionary-to-a-text-file – Equinox Nov 10 '21 at 16:08
  • Don't use `sum` as [function] name – buran Nov 10 '21 at 16:20

3 Answers3

1
dict1={"Length":36,"Reverse":"TTTTTTTTTTGGGGGGGAAAAAAAAAAAAAAAATAT","complement":"ATATTTTTTTTTTTTTTTTCCCCCCCAAAAAAAAAA","Reverse and complement":"AAAAAAAAAACCCCCCCTTTTTTTTTTTTTTTTATA","gc_percentage":5.142857142857143}

with open("output.txt","w") as data:
    for k,v in dict1.items():
        append_data=k+" "+str(v)
        data.write(append_data)
        data.write("\n")

Output:

Length 36
Reverse TTTTTTTTTTGGGGGGGAAAAAAAAAAAAAAAATAT
complement ATATTTTTTTTTTTTTTTTCCCCCCCAAAAAAAAAA
Reverse and complement AAAAAAAAAACCCCCCCTTTTTTTTTTTTTTTTATA
gc_percentage 5.142857142857143
Bhavya Parikh
  • 3,304
  • 2
  • 9
  • 19
0

You can use open method to create a new file, and write your output. And as @Blackgaurd told you, this isn't a code-writing service.

Also I wrote this code really quickly so some syntax error may occur

import sys
import datetime
from clases.sequence import Sequence
from clases.read_file import Read_file
from fastapi import FastAPI

app = FastAPI()

@app.get("/DNA_toolkit")
def sum(input: str):                        # pass the sequence in, this time as a query param
    DNA = Sequence(input)                    # get the result (i.e., 4)
    res = {"Length": DNA.length(),         # return the response
        "Reverse": DNA.reverse(),
        "complement":DNA.complement(),
        "Reverse and complement": DNA.reverse_and_complement(),
        "gc_percentage": DNA.gc_percentage()
        }

    #with open('result.txt', 'w+') as resFile:
        #for i in res:
            #resFile.write(i+" "+res[i]+"\n")

        #resFile.close()

        # Undo the above comment if you don't want to save result into 
        #file with unique id, else go with the method I wrote below...
    filename = str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time()).replace(':', '.')
    with open(filename+'.txt', 'w+') as resFile:
        for i in res:
            resFile.write(i+" "+res[i]+"\n")

        resFile.close()

    return {"Length": DNA.length(),         # return the response
        "Reverse": DNA.reverse(),
        "complement":DNA.complement(),
        "Reverse and complement": DNA.reverse_and_complement(),
        "gc_percentage": DNA.gc_percentage()
        }
  • 2
    You are saving the file on the API server. Probably, the OP needs to save it upon the API call from a client – floatingpurr Nov 10 '21 at 16:16
  • Well I have no idea about the FastApi, so I really don't know, I've worked with flask. And as for saving the file on the client side, the OP can make the just raise a download request and the file will start downloading – SuhailHasan Nov 10 '21 at 16:26
  • I see. Pay attention to data modifications since that code overwrites the same file on the server upon each API call. I mean: someone could send another request to this endpoint before you download the file. – floatingpurr Nov 10 '21 at 16:34
  • Yes you are correct, but that's going wayyy to far, OP can code it in that way, by writing an algorithm which will check the file if it already exists, then it would just assign a particular unique id to the filename Ex- `with open('file_~uniqueid~.txt', 'w+'): ........` – SuhailHasan Nov 11 '21 at 07:44
  • You might want to add this information in your answer. – floatingpurr Nov 11 '21 at 09:21
  • I have made some changes with respect to your comment – SuhailHasan Nov 11 '21 at 15:42
0

I gonna assume that you have already got your data somehow calling your API.

# data = request.get(...).json()

# save to file:
with open("DNA_insights.txt", 'w') as f: 
    for k, v in data.items(): 
        f.write(f"{k}: {v}\n")
floatingpurr
  • 7,749
  • 9
  • 46
  • 106