How to create a simple REST api WEB application with Python - python

We can make REST api application with spring boot by start.spring.io web site easily, anyone know any good website through which I can get the skeleton REST api project with python? My intention is to make REST api application with python.

One of the ways to do this is by using the requests module in Python. Import it into your code with the following command:
import requests
Now, each API is different, so you'll have to see with the vendor what the requirements are. For testing and learning purposes, I recommend using httpbin (https://httpbin.org). You can test pretty much anything there.
Here are a few simple requests:
#returning status
url = 'https://httpbin.org/post'
response = requests.post(url)
print(response.status_code)
print(response.ok)
#sending data/getting text response
url = 'https://httpbin.org/post'
params = {'Jello':'World'}
response = requests.post(url, params=params)
print(response.text)
#sending data/getting json response
url = 'https://httpbin.org/post'
params = {'Jello':'World'}
response = requests.post(url, params=params)
print(response.json())
#sending time data to server
import datetime
url = 'https://httpbin.org/post'
params = {'Time':f'{datetime.datetime.now()}'}
response = requests.post(url, params=params)
print(response.text)
#Params vs Data
#params
url = 'https://httpbin.org/post'
params = {'username':'jsmith','password':'abc123'}
response = requests.post(url, params=params)
print(response.text)
#data
url = 'https://httpbin.org/post'
payload = {'username':'jsmith','password':'abc123'}
response = requests.post(url, data=payload)
print(response.text)
# ********* HEADERS **********
url = 'https://httpbin.org/get'
response = requests.get(url)
print(response.text)
url = 'https://httpbin.org/post'
headers = {'content-type': 'multipart/form-data'}
response = requests.post(url,headers=headers)
print(response.request.headers) #client request headers
print(response.headers) #server response headers
print(response.headers['content-type']) #request header value from server
To use actual APIs, I suggest RapidAPI (https://rapidapi.com/), which is a hub where you can connect to thousands of APIs. HEre is a sample code using Google translate:
#RapidAPI
#Google Translate
import requests
url = "https://google-translate1.p.rapidapi.com/language/translate/v2"
text = 'Ciao mondo!'
to_lang = 'en'
from_lang = 'it'
payload = f"q={text}&target={to_lang}&source={from_lang}"
headers = {
'content-type': "application/x-www-form-urlencoded",
'accept-encoding': "application/gzip",
'x-rapidapi-host': "google-translate1.p.rapidapi.com",
'x-rapidapi-key': "your-API-key"
}
response = requests.post(url, data=payload, headers=headers)
print(response.json()['data']['translations'][0]['translatedText'])

Related

Python Session request is parsing the data argument wrongly

I'm trying to send a request to a server and also a json as data argument. If I use straight request, it works, but when I use session I get a bad request as result.
THIS WORKS:
import request
url = "https://whatever/api/v1/dosomething"
data = {"client":{"id":100},"job":{"name":"software developer","field_id":[1,2,3],"level":20}}
headers = {'Content-type': 'application/json'}
r = requests.get(url, data=json.dumps(data), headers=headers)
When I check r.request.body, I get the following:
'{"client": {"id": 100}, "job": {"name": "software developer", "field_id": [1, 2, 3], "level": 20}}'
THIS DOES NOT WORK:
When I try to use Session though, the request.body gets messed up.
url = "https://whatever/api/v1/dosomething"
data = {"client":{"id":100},"job":{"name":"software developer","field_id":[1,2,3],"level":20}}
headers = {'Content-type': 'application/json'}
s = requests.Session()
r = s.get(url, headers=headers, data=data, verify=False)
I get a bad request as a result of the code above, and when I check r.request.body:
client=id&job=name&job=field_id&job=level
I think I'm getting a bad request because of the request.body that got parsed in a wrong way, but I am not finding how to parse it correctly.
I already tried to use:
req = Request('GET', url, data=data, headers=headers)
prepped = req.prepare()
resp = s.send(prepped)
Can someone please help?
Thanks
You also need to json.dumps(data) when sending json with session.
So it will be
r = s.get(url, headers=headers, data=json.dumps(data), verify=False)
Not
r = s.get(url, headers=headers, data=data, verify=False)

How to access the github API via requests in python?

I am trying to access the github API via requests with python (Answers in similar questions here and here do not help).
Using curl, I am able to get a list of recent commits for a project, e.g.
curl -H "Accept: application/vnd.github.inertia-preview+json Authorization: token a0d42faabef23ab5b5462394373fc133ca107890" https://api.github.com/repos/rsapkf/42/commit
Trying to use the same setup in python with requests I tried to use
url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json", "Authorization": "token a0d42faabef23ab5b5462394373fc133ca107890"}
r = requests.get(url, headers=headers)
as well as
url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json"}
my_username = "someuser"
my_token = "a0d42faabef23ab5b5462394373fc133ca107890"
r = requests.get(url, headers=headers, auth=(my_username, my_token))
but in both cases I get the response
{'documentation_url': 'https://docs.github.com/rest',
'message': 'Bad credentials'}
What am I missing here?
No Authentication is required. The following works:
url = "https://api.github.com/repos/rsapkf/42/commits"
headers = {"Accept": "application/vnd.github.inertia-preview+json"}
r = requests.get(url, headers=headers)

How to get the request from api having account key

import requests
import json
def test_request_response():
# Send a request to the API server and store the response.
data = { 'username' : 'sxxxt#xxx.com', 'password' : 'xxxxe' }
headers = {'Content-type': 'application/json'}
response = requests.get('https://xx.xxx.com/xx/xx',headers=headers,data=json.dumps(data))
return response
test_request_response()
output
I have an api key also API_KEY = '0x-x-x-x0 is there any I can give API_KEY in requests.get as like username and password
example in headers headers = {'Content-type': 'application/json','X-IG-API-KEY':'0x-x-x-x0'}
is this what you are looking for ?
from requests.auth import HTTPBasicAuth
import requests
url = "https://api_url"
headers = {"Accept": "application/json"}
auth = HTTPBasicAuth('apikey', '1234abcd')
files = {'filename': open('filename','rb')}
req = requests.get(url, headers=headers , auth=auth , files=files)
reference : Calling REST API with an API key using the requests package in Python

Issues Accessing SOAP service with Python

I am attempting to access the NJTransit API, I have successfully queried it using the Postman application but no matter what I try I cannot get python to successfully return the desired query.
Using suds:
from suds.client import Client
url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx?wsdl"
client = Client(url, cache = None)
from suds.sax.element import Element
auth = Element('UserCredentials')
auth.append(Element('userName').setText(my_username))
auth.append(Element('password').setText(my_password))
client.set_options(soapheaders = auth)
client = Client(url, cache = None)
result = client.service.getTrainScheduleJSON("NY")
This results in "none".
I've also attempted to use the preformatted request suggested by the Postman app, however I keep getting a 404 error.
import requests
url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx"
querystring = {"wsdl":""}
payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Header>\n <UserCredentials xmlns=\"http://microsoft.com/webservices/\">\n <userName>---</userName>\n <password>---</password>\n </UserCredentials>\n </soap:Header>\n <soap:Body>\n <getTrainScheduleJSON xmlns=\"http://microsoft.com/webservices/\">\n <station>NY</station>\n </getTrainScheduleJSON>\n </soap:Body>\n</soap:Envelope>"
headers = {
'content-type': "text/xml; charset=utf-8",
'host': "traindata.njtransit.com",
'soapaction': "http//microsoft.com/webservices/getTrainScheduleJSON"
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
I would greatly appreciate any help/insight.
You never want to set the "Host" header, this is will be done by requests.
The 404 is triggered by the wrong SOAPAction. There is a missing : after http.
The following snippet is working fine for me.
import requests
url = "http://traindata.njtransit.com:8090/NJTTrainData.asmx"
querystring = {"wsdl":""}
payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Header>\n <UserCredentials xmlns=\"http://microsoft.com/webservices/\">\n <userName>---</userName>\n <password>---</password>\n </UserCredentials>\n </soap:Header>\n <soap:Body>\n <getTrainScheduleJSON xmlns=\"http://microsoft.com/webservices/\">\n <station>NY</station>\n </getTrainScheduleJSON>\n </soap:Body>\n</soap:Envelope>"
headers = {
'content-type': "text/xml; charset=utf-8",
'soapaction': 'http://microsoft.com/webservices/getTrainScheduleJSON'
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print response
print(response.text)

how to use Google Shortener API with Python

I want to write an app to shorten url. This is my code:
import urllib, urllib2
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = urllib.urlencode({'longUrl':url})
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
postdata,
headers
)
ret = urllib2.urlopen(req).read()
return json.loads(ret)['id']
when I run the code to get a tiny url, it throws an exception: urllib2.HTTPError: HTTP Error 400: Bad Requests.
What is wrong with this code?
I tried your code and couldn't make it work either, so I wrote it with requests:
import requests
import json
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(post_url, data=json.dumps(payload), headers=headers)
print(r.text)
Edit: code working with urllib:
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url'
postdata = {'longUrl':url}
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
json.dumps(postdata),
headers
)
ret = urllib2.urlopen(req).read()
print(ret)
return json.loads(ret)['id']
I know this question is old but it is high on Google.
Another thing to try is the pyshorteners library it is very simple to implement.
Here is a link:
https://pypi.python.org/pypi/pyshorteners
With an api key:
import requests
import json
def shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(API_KEY)
payload = {'longUrl': url}
headers = {'content-type': 'application/json'}
r = requests.post(post_url, data=json.dumps(payload), headers=headers)
return r.json()

Categories

Resources