How to POST a single parameter as JSON in FastAPI? - python-3.x

I have a working model using transformers pipeline and I want to use it with FastAPI to send post requisitions and get the response.
The model works this way:
#Loading the model
classifier = pipeline(path_to_model)
#Making predictions:
classifier(txt)
The output is a list of dicts.
My code is:
app = FastAPI()
#app.post("/predictions")
def extract_predictions(text):
text = text.lower()
out=classifier(text)
return {
"text_message": text,
"predictions": out
}
I can get predictions if I use localhost:8000/docs, but when I use postman or insominia and body(JSON) {"text":"any string"} I get "field_required"
The model takes a string as an input and my postman request uses a JSON body. How can I update model to get the input as JSON?

The text attribute, as is currently defined, is expected to be a query parameter, not body (JSON) parameter. Hence, you can either send it as a query parameter when POSTing your request, or define it using Body field (e.g., text: str = Body(..., embed=True)), so that is expected in the body of the request as JSON. Please have a look at the answers here and here for more details.

Related

How to get the result from API not only the response code

I am trying to get the result of foreign currency exchange rate but on sending a Get request to the API "https://data.fixer.io/api/".." instead of getting a result, I am getting a response code 200 but no exchange rates are there
def main():
res=requests.get("http://data.fixer.io/api/latest? access_key = YOUR_ACCESS_KEY& base = INR& symbols = USD")
if res.status_code!=200:
raise Exception("Error : APIdidn't work")
print(res)
Expected result:
{
"success":true,
"timestamp":1559223544,
"base":"INR",
"rates":{
"USD":0.014,
}
}
Actual result :
<Response [200]>
To use the data that you're pulling from the API - you need to convert it to readable json. DeepSpace is correct - you need to use res.json()
Append the data to a variable if you want to iterate through it or utilize it further.
data = res.json()

Post multipart form with multiple file uploads using python requests

I have demographics information extracted for some people in the form of list of python dictionaries(each dict for an individual). Also I need to upload the document from where I extracted the data (pdf/word). I tried Multipart form submission using Python requests which because of some reason does not seem to work.
The API expects two keys 'files' and 'data'
'files' is a list of file objects
'data' is a list of dicts which is stringified using json.dumps (API requirements)
pay_part= [{"umr":"","age":"","gender":"","first_name":"","middle_name":"","last_name":"","phone":"","address":"","admission_date":"","lab":"","discharge_date":"","ip_number":"","diagnosis":"","reason":"","treatment":"","medications":"","expired_date":"","instructions":"","review_date":"","procedure":"","notes":"","physician":"","filename":""},{"umr":"","age":"","gender":"","first_name":"","middle_name":"","last_name":"","phone":"","address":"","admission_date":"","lab":"","discharge_date":"","ip_number":"","diagnosis":"","reason":"","treatment":"","medications":"","expired_date":"","instructions":"","review_date":"","procedure":"","notes":"","physician":"","filename":""}]
multipart_data = MultipartEncoder(
fields={
"file":[('file.docx',open('13427.docx', 'rb'),'text/plain'),
('file.docx',open('13427.docx', 'rb'),'text/plain')],
"payload": json.dumps(pay_part)
}
)
response = requests.post(url, data=multipart_data, headers={'Content-Type': 'multipart_data.content_type; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW', 'userid': sUserID,'metaid': metaid,'postman-token':postmanToken})
print(response.text)
While forming the multipart form object I get an error
"AttributeError: 'tuple' object has no attribute 'encode'".
I believe this has to do something with creating file objects as a binary and storing in list.
Thanks in advance!
I got it to work!
Just send your json object using the argument ‘data’ and a list of your file objects using the argument ‘files’ as shown below.
I removed from the header argument “'Content-Type': 'multipart_data.content_type; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW'”
The post request was made as a multipart post
Code:-
fields={'payload': json.dumps(pay_part)})
response = requests.post(url, data=fields,files =[('file',open('13385.docx', 'rb')),('file',open('13385.docx', 'rb'))], headers={'userid': sUserID,'metaid': metaid,'postman-token':postmanToken})
print(response.text)

How to pass params to a HTTP request (teststep) in a SOAP UI Test case using groovy and run it

I am writing a groovy script to execute/automate my test suite. In one test case i have a HTTPRequest where i have a request URL, parameters( username and password) and method( GET) to get a token-id and then i would pass that token id to my next step( a SOAP request)to get the data.
I am stuck at a point where i need to pass the params(username and password), request URL and method(GET) using groovy.
I have a test step created manaully under a test case, i just need to pass the params
as i search online i got to know how to pass headers,url to a SOAP request which is like below
def headers = new StringToStringMap()
testRunner = new com.eviware............WsdlTestCaseRunner(myTestCase,null);
testStepContext = new com.eviware.soapui........WsdlTestRunContext(testsetp);
headers.put("apikey", "abcd")
teststep.getTestRequest().setRequestHeaders(headers)
teststep.getHttpRequest().setEndpoint(encpointurl);
testsetp.run(testRunner ,testStepContext )
but i looking to know how to pass params to a http request(test step) and run it.
Add a Properties teststep to your testcase. Just let it keep the default "Properties" name.
Add the properties to the Properties teststep, that you need to transfer
Inside your groovy teststep, you may set the properties using something like:
def properties = testRunner.testCase.getTestStepByName("Properties");
properties.setPropertyValue("name", "value");
Add the parameters directly in your request using variables in the format ${Properties#name} and replace "name" with the actual parameter name. This can be done both in the request body and in the URL if you should wish to do so.
It can be done completely in groovy by using groovy.json.JsonBuilder Class.
def body = new StringToStringMap()
def jsonbildr = new JsonBuilder()
body.put("username","Hackme")
body.put("password","LockUout")
def root = jsonbildr body
jsonbildr = jsonbildr.toPrettyString()
log.info(jsonbildr)
testStep.setPropertyValue("Request", jsonbildr)
Output :
{
"password": "LockUout",
"username": "Hackme"
}

Can't extract data from RESTClient response

I am writing my first Groovy script, where I am calling a REST API.
I have the following call:
def client = new RESTClient( 'http://myServer:9000/api/resources/?format=json' )
That returns:
[[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]]
I am trying to get the field level, like this:
def level_value = client.get( path : 'msr/data/level' )
However, when I print the value of the variable obtained:
println level_value.getData()
I get the whole JSON object instead of the field:
[[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]]
So, what am I doing wrong?
Haven't looked at the docs for RESTClient but like Tim notes you seem to have a bit of a confusion around the rest client instance vs the respons object vs the json data. Something along the lines of:
def client = new RESTClient('http://myServer:9000/api/resources/?format=json')
def response = client.get(path: 'msr/data/level')
def level = response.data[0].msr[0].data.level
might get you your value. The main point here is that client is an instance of RESTClient, response is a response object representing the http response from the server, and response.data contains the parsed json payload in the response.
You would need to experiment with the expression on the last line to pull out the 'level' value.

How do I set a value in JSON response in Groovy script in SOAP UI

I have two REST request which I am trying to run in SOAP UI. I want to feed response from one REST request to the other REST request. I am using property transfer for this. I first want to modify a Value in Response from 1st request and then feed it . I am trying this
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
// request
def request = '''{"data":{
"supplementaryMessages" : [ ],
"requisitionHeaders" : [ {
"dataOperation" : "UPDATE"
} ]
}}'''
// parse the request
def jsonReq = new JsonSlurper().parseText(request);
// get the response where you've the values you want to get
// using the name of your test step
responseContent = testRunner.testCase.getTestStepByName("Fetch1").getPropertyValue("response")
// parse response
def jsonResp = new JsonSlurper().parseText(responseContent)
// get the values from your first test response
// and set it in the request of the second test
jsonResp.data.requisitionHeaders.dataOperation = jsonReq.data.requisitionHeaders.dataOperation
When I run this I am getting the Type Mismatch error .It could be very simple issue but I am new to Groovy .

Resources