Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
API in Python and Postman
#1
hello! I'm a beginner in Python and i'm doing an internship in an energy company. So the company asked me to write a small python code so that i could retrieve information from different API address to our server.
I first used Postman, and it was very easy to have access to the information:
I told Postman the API address: http://www.adress.com, the API key, and made a GET request to retrieve some information.

Then I used a POST request and had to write a JSON Script in the "Body" section of Postman to have my informations. The following script for example:

{
"structures_name" : [“Ma structure”],
"boitiers_uid" : [“12:34:56:78:90”],
"dates" : ["2016­06­06 06:06","2016­07­07 06:06"],
"IO_name" : ["Mon entrée","Ma sortie"],
"IO_type": ["TEMPERATURE"],
"period_length": ["year","month"]
}

Now I want to do the same thing like Postman but in python, I'm using the package requests. I can do the GET request. But I don't know how to write the "body script in JSON" in Python, I tried different things but it's not working.
Here is my python script:

import requests
payload = {'api_key':'API_KEY_REMOVED'}

#Requete GET
resp = requests.get('http://www.adress.com/api/V1/org', params=payload)
print (resp.status_code) 
print (resp.json())

#Requete POST
r = requests.post('http://www.adress.com/api/V1/struct', json=payload)
print(r.json())

data =  {'structures_names': ["ENERGIE AGENCE - POST LU"], 
         'dates' : ["2018-­07-­06 06:06","2018-­07-­30 06:06"],
         'IO_name' : ["temp bureau minerais 1 etage 3"],
         'IO_type': ["TEMPERATURE"],
         'period_length': ["year","month"]}[/b]

r = requests.post('http://www.ewattchcloud.fr/api/V1/struct?api_key=API_KEY_REMOVED', json = data)
print (r.status_code)
print(r.json())
In the POST request, I don't know how to write the "data" so that Python understands what I want to do...
Does anyone know a bit about API, Postman and python? I hope I was clear enough... Thank you for your help, or at least thank you for taking the time to read my post!
Reply
#2
Try to set up the headers.

import requests
import json

headers = {'Content-type': 'application/json'}
data =  {'structures_names': ["ENERGIE AGENCE - POST LU"], 
         'dates' : ["2018-­07-­06 06:06","2018-­07-­30 06:06"],
         'IO_name' : ["temp bureau minerais 1 etage 3"],
         'IO_type': ["TEMPERATURE"],
         'period_length': ["year","month"]}

data_json = json.dumps(data)
url = 'http://www.ewattchcloud.fr/api/V1/struct?api_key=API_KEY_REMOVED'
r = requests.post(url, data=data_json, headers=headers)
print (r.status_code)
print(r.json())
Reply
#3
Thank you! i tried your code, I don't really know why, but i have something but not the complete information. and I think that the package is called simplejson? not json in python, right?

I actually found the solution yesterday! the code bellow is working for people who are interested:
import requests

#lien URL
url = "http://www.address.com"

#clé API 
apikey = {"api_key":"API_KEY_REMOVED"}

def post():
    """fonction pour la requete POST"""
    payload = "{\r\n\"structures_name\" : [\"structure\"],\r\n\r\n\"dates\" : [\"2018-08-21 06:06\",\"2018-08-22 06:06\"],\r\n\"IO_name\" : [\"capteur 1\"],\r\n\"IO_type\": [\"TEMPERATURE\"],\r\n\"period_length\": [\"month\",\"day\",\"hour\"]\r\n}"
    headers = {
            'Content-Type': "application/json",
            'Cache-Control': "no-cache",
            }
    response = requests.post(url, data=payload, headers=headers, params=apikey)

    print(response.text)
Still, thank you for your answer!
Reply
#4
Good!

About the json module: JSON
Reply
#5
(Aug-29-2018, 08:17 AM)melo Wrote: I actually found the solution yesterday! the code bellow is working for people who are interested:
Now you not sending JSON,your first post look more correct(you send JSON),but it can also depend on the server.

Requests has for long time had json parameter supported.
Can also drop Content-Type,Requests will fix it.
So the shorter version.
>>> import requests
>>> 
>>> response = requests.post('http://httpbin.org/post', json={'Python': 'Forum'})
>>> response.status_code
200
>>> response.json()
{'args': {},
 'data': '{"Python": "Forum"}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '19',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.19.1'},
 'json': {'Python': 'Forum'},
 'origin': '95.143.193.192',
 'url': 'http://httpbin.org/post'}

>>> response.json()['json']
{'Python': 'Forum'}
>>> response.json()['json']['Python']
'Forum'
httpbin is test server for HTTP Request & Response Service.
Can test with your data.
import requests

headers = {'Content-type': 'application/json'}
data = {
    "structures_names": ["ENERGIE AGENCE - POST LU"],
    "dates": ["2018­07-06 06:06", "2018­07­30 06:06"],
    "IO_name": ["temp bureau minerais 1 etage 3"],
    "IO_type": ["TEMPERATURE"],
    "period_length": ["year", "month"],
}

response = requests.post('http://httpbin.org/post', json=data, timeout=5)
Test server response.
>>> response.status_code
200

>>> response.json()
{'args': {},
 'data': '{"structures_names": ["ENERGIE AGENCE - POST LU"], "dates": '
         '["2018\\u00ad07-06 06:06", "2018\\u00ad07\\u00ad30 06:06"], '
         '"IO_name": ["temp bureau minerais 1 etage 3"], "IO_type": '
         '["TEMPERATURE"], "period_length": ["year", "month"]}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '227',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.19.1'},
 'json': {'IO_name': ['temp bureau minerais 1 etage 3'],
          'IO_type': ['TEMPERATURE'],
          'dates': ['2018\xad07-06 06:06', '2018\xad07\xad30 06:06'],
          'period_length': ['year', 'month'],
          'structures_names': ['ENERGIE AGENCE - POST LU']},
 'origin': '85.165.177.151',
 'url': 'http://httpbin.org/post'}

>>> print(response.json()['json']['dates'][0])
2018-­07-06 06:06
If look at text on server we similar payload that you send(should not be needed to send this).
>>> print(response.text)
{
  "args": {}, 
  "data": "{\"structures_names\": [\"ENERGIE AGENCE - POST LU\"], \"dates\": [\"2018\\u00ad07\\u00ad06 06:06\", \"2018\\u00ad07\\u00ad30 06:06\"], \"IO_name\": [\"temp bureau minerais 1 etage 3\"], \"IO_type\": [\"TEMPERATURE\"], \"period_length\": [\"year\", \"month\"]}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "232", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.19.1"
  }, 
  "json": {
    "IO_name": [
      "temp bureau minerais 1 etage 3"
    ], 
    "IO_type": [
      "TEMPERATURE"
    ], 
    "dates": [
      "2018\u00ad07\u00ad06 06:06", 
      "2018\u00ad07\u00ad30 06:06"
    ], 
    "period_length": [
      "year", 
      "month"
    ], 
    "structures_names": [
      "ENERGIE AGENCE - POST LU"
    ]
  }, 
  "origin": "95.143.193.192", 
  "url": "http://httpbin.org/post"
}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  upload image with generated code from Postman does not work magic7598 0 1,697 Nov-30-2019, 10:32 AM
Last Post: magic7598
  [split] API in Python and Postman fioranosnake 26 8,148 Nov-20-2019, 07:30 PM
Last Post: fioranosnake

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020