Skip to content

Commit

Permalink
Develop (#5)
Browse files Browse the repository at this point in the history
* code quality - flake8

* move the examples into their own file for clarity

* move the examples into their own file for clarity
  • Loading branch information
Bobspadger committed Mar 29, 2018
1 parent 3cba28a commit c75a820
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 97 deletions.
3 changes: 0 additions & 3 deletions royal_mail_rest_api/api.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
# -*- coding: utf-8 -*-

"""Main module."""
import requests
from .errors import NotAuthorised, GeneralError


class RoyalMailBaseClass():
"""
BASE CLASS FOR SHIPPING
"""
url = 'https://api.royalmail.net'

1 change: 1 addition & 0 deletions royal_mail_rest_api/errors.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
class NotAuthorised(Exception):
pass


class GeneralError(Exception):
pass
59 changes: 59 additions & 0 deletions royal_mail_rest_api/example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import json
from royal_mail_rest_api.tools import RoyalMailBody
from royal_mail_rest_api.shipping import ShippingApi
from royal_mail_rest_api.get_credentials import return_credentials

if __name__ == '__main__':

creds = return_credentials()

body = RoyalMailBody('Delivery')
body.add_ship_date(None)
body.add_service('P', 1, 'TPN', 'T', True, ['14'])
body.customer_reference = 'D123456'
body.department_reference = 'Q123456'
body.sender_reference = 'A123456'
body.add_items(1, 100, 'g')
body.add_receipient_contact('Joe Bloggs', 'joe.bloggs@royalmail.com', None, '07970810000')
body.add_receipient_address('Broadgate Circle', 'London', None, 'EC1A 1BB', country='GB', building_number='1',
address_line2='Add line 2', address_line3='Add line 3', building_name='My building')

my_rm_body = body.return_domestic_body()


print(json.dumps(my_rm_body))

print(my_rm_body)


CLIENT_ID = creds['royal_mail']['CLIENT_ID']
CLIENT_SECRET = creds['royal_mail']['CLIENT_SECRET']
USERNAME = creds['royal_mail']['USERNAME']
PASSWORD_HASHED = creds['royal_mail']['PASSWORD_HASHED']
my_shipping = ShippingApi(CLIENT_ID, CLIENT_SECRET, USERNAME, PASSWORD_HASHED)
my_shipping.get_token()

post_shipping = my_shipping.post_domestic(my_rm_body)
tracking_ref = post_shipping['completedShipments'][0]['shipmentItems'][0]['shipmentNumber']
label = my_shipping.put_shipment_label(tracking_ref)

# new_data = {
# 'recipientContact': {
# 'name': 'Alex Hellier'
# }
# }

body.add_receipient_contact('Alex Hellier', 'alex@me.com', 'Alex S Hellier', '123455')
new_data = body.return_domestic_update_boy()
change_name = my_shipping.put_shipment(tracking_ref, new_data)
new_label = my_shipping.put_shipment_label(tracking_ref)

# print(tracking_ref)
# delete_shipping = my_shipping.delete_shipment(tracking_ref)

# print(delete_shipping)
# manifest_info = {'yourReference': '123'}
# manifest_data = my_shipping.post_manifest(manifest_info)
# print(manifest_data)
# manifest_label = my_shipping.put_manifest(manifest_batch_number=5)
# print(manifest_label)
47 changes: 22 additions & 25 deletions royal_mail_rest_api/shipping.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ def __init__(self, client_id, client_secret, username, password):
self.password = password
self._create_authentication_header()


def _create_authentication_header(self):
self.header = {'X-IBM-Client-Id': self.client_id,
'X-IBM-Client-Secret': self.client_secret,
Expand All @@ -39,9 +38,9 @@ def _create_authentication_header(self):

def _create_token_header(self):
self.tokenheader = {'X-IBM-Client-Id': self.client_id,
'X-IBM-Client-Secret': self.client_secret,
'x-rmg-auth-token': self.token,
'accept': 'application/json'}
'X-IBM-Client-Secret': self.client_secret,
'x-rmg-auth-token': self.token,
'accept': 'application/json'}

def get_token(self):
"""
Expand All @@ -54,12 +53,13 @@ def get_token(self):
Description
-----------
This method will accept a DMO/NEOPOST user name and password. On successful validation of the user credential it will issue a JWT token to the user which will be valid for 4 hours. On subsequent requests, user will pass the JWT token in the request header.
This method will accept a DMO/NEOPOST user name and password.
On successful validation of the user credential it will issue a JWT token to the user which will be
valid for 4 hours. On subsequent requests, user will pass the JWT token in the request header.
:return:
"""


result = requests.get('{}{}'.format(self.url, self.token_url), headers=self.header)
result.raise_for_status()
result = result.json()
Expand All @@ -76,11 +76,12 @@ def post_domestic(self, data):
Description
-----------
This method will take a domestic shipment request in the body and on successful response, it will return the shipment numbers and item details.
This method will take a domestic shipment request in the body and on successful response,
it will return the shipment numbers and item details.
:return:
"""
data = data
result = requests.post('{}{}'.format(self.url,self.post_domestic_url), json=data, headers=self.tokenheader)
result = requests.post('{}{}'.format(self.url, self.post_domestic_url), json=data, headers=self.tokenheader)
result.raise_for_status()
return result.json()

Expand All @@ -94,12 +95,15 @@ def put_shipment(self, shipment_number, data):
Description
-----------
Update a shipment. Send a shipment request in body. On successful response, it will return shipment number and warnings. Service related information can not be updated, and if passed as part of request, it will be ignored.
Update a shipment. Send a shipment request in body. On successful response,
it will return shipment number and warnings. Service related information can not be updated,
and if passed as part of request, it will be ignored.
:return:
"""
# TODO: returning 400 errors at present
result = requests.put('{}{}{}'.format(self.url, self.put_shipment_update_url, shipment_number), json=data, headers=self.tokenheader)
result = requests.put('{}{}{}'.format(self.url, self.put_shipment_update_url, shipment_number), json=data,
headers=self.tokenheader)
result.raise_for_status()
return result.json()

Expand All @@ -111,11 +115,11 @@ def delete_shipment(self, shipment_number):
:return:
"""
result = requests.delete('{}{}{}'.format(self.url, self.delete_shipment_url, shipment_number), headers=self.tokenheader)
result = requests.delete('{}{}{}'.format(self.url, self.delete_shipment_url, shipment_number),
headers=self.tokenheader)
result.raise_for_status()
return result.json()


def put_shipment_label(self, shipment_number):
"""
Expand All @@ -125,7 +129,8 @@ def put_shipment_label(self, shipment_number):
:return:
"""
result = requests.put('{}{}{}/label'.format(self.url, self.put_shipment_label_url, shipment_number), headers=self.tokenheader)
result = requests.put('{}{}{}/label'.format(self.url, self.put_shipment_label_url, shipment_number),
headers=self.tokenheader)
result.raise_for_status()
return result.json()

Expand All @@ -138,7 +143,8 @@ def post_manifest(self, manifest_options=None):
:return:
"""
result = requests.post('{}{}'.format(self.url, self.post_manifest_url), json=manifest_options, headers=self.tokenheader)
result = requests.post('{}{}'.format(self.url, self.post_manifest_url), json=manifest_options,
headers=self.tokenheader)
result.raise_for_status()
return result.json()

Expand All @@ -157,19 +163,10 @@ def put_manifest(self, sales_order_number=None, manifest_batch_number=None):

query_params = '&'.join(params)

result = requests.put('{}{}?{}'.format(self.url, self.post_manifest_url, query_params), headers=self.tokenheader)
result = requests.put('{}{}?{}'.format(self.url, self.post_manifest_url, query_params),
headers=self.tokenheader)
result.raise_for_status()
return result.json()


if __name__ == '__main__':
from royal_mail_rest_api.get_credentials import return_credentials
creds = return_credentials()

CLIENT_ID = creds['royal_mail']['CLIENT_ID']
CLIENT_SECRET = creds['royal_mail']['CLIENT_SECRET']
USERNAME = creds['royal_mail']['USERNAME']
PASSWORD_HASHED = creds['royal_mail']['PASSWORD_HASHED']

shipping_api = ShippingApi(CLIENT_ID, CLIENT_SECRET, USERNAME, PASSWORD_HASHED)
token = shipping_api.get_token()
76 changes: 8 additions & 68 deletions royal_mail_rest_api/tools.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import datetime

class RoyalMailBody():

class RoyalMailBody:
def __init__(self, shipment_type):
self.receipient = None
self.address = None
Expand Down Expand Up @@ -54,11 +55,12 @@ def return_domestic_update_boy(self):

return domestic_body

def remove_none_values(self, iterable):
@staticmethod
def remove_none_values(iterable):
"""
take out values of None by removing the key
:param iterable:
:return:
:return: dictionary
"""

new_dict = {k: v for k, v in iterable.items() if v is not None}
Expand All @@ -72,7 +74,6 @@ def _check_ship_type(self, shipment_type):
else:
self.shipment_type = shipment_type.lower()


def add_ship_date(self, date_obj=None):
"""
take a datetime object and format it to royal mails Y-m-d format
Expand All @@ -98,7 +99,6 @@ def add_service(self, format=None, occurrence=None, offering=None, _type=None, s

self.service = service


def add_receipient_contact(self, name, email, complementary_name=None, telephone=None):
receipient = {
"name": name,
Expand All @@ -110,10 +110,9 @@ def add_receipient_contact(self, name, email, complementary_name=None, telephone
# receipient = self.remove_none_values(receipient)
self.receipient = receipient


def add_items(self, number, weight, unit_of_measure):
items = [{
"count": number ,
"count": number,
"weight": {
"unitOfMeasure": unit_of_measure,
"value": weight
Expand All @@ -122,9 +121,8 @@ def add_items(self, number, weight, unit_of_measure):

self.items = items


def add_receipient_address(self, address_line1, post_town, county, postcode, country, building_name=None, building_number=None,
address_line2=None, address_line3=None):
def add_receipient_address(self, address_line1, post_town, county, postcode, country, building_name=None,
building_number=None, address_line2=None, address_line3=None):
address = {
"buildingName": building_name,
"buildingNumber": building_number,
Expand All @@ -141,61 +139,3 @@ def add_receipient_address(self, address_line1, post_town, county, postcode, cou
self.address = address




if __name__ == '__main__':
from royal_mail_rest_api.get_credentials import return_credentials
creds = return_credentials()

body = RoyalMailBody('Delivery')


body.add_ship_date(None)
body.add_service('P', 1, 'TPN', 'T', True, ['14'])
body.customer_reference = 'D123456'
body.department_reference = 'Q123456'
body.sender_reference = 'A123456'
body.add_items(1, 100, 'g')
body.add_receipient_contact('Joe Bloggs', 'joe.bloggs@royalmail.com', None, '07970810000')
body.add_receipient_address('Broadgate Circle', 'London', None, 'EC1A 1BB', country='GB', building_number='1', address_line2='Add line 2', address_line3='Add line 3', building_name='My building')


my_rm_body = body.return_domestic_body()
import json

print(json.dumps(my_rm_body))

print(my_rm_body)

from royal_mail_rest_api.shipping import ShippingApi
CLIENT_ID = creds['royal_mail']['CLIENT_ID']
CLIENT_SECRET = creds['royal_mail']['CLIENT_SECRET']
USERNAME = creds['royal_mail']['USERNAME']
PASSWORD_HASHED = creds['royal_mail']['PASSWORD_HASHED']
my_shipping = ShippingApi(CLIENT_ID, CLIENT_SECRET, USERNAME, PASSWORD_HASHED)
my_shipping.get_token()


post_shipping = my_shipping.post_domestic(my_rm_body)
tracking_ref= post_shipping['completedShipments'][0]['shipmentItems'][0]['shipmentNumber']
label = my_shipping.put_shipment_label(tracking_ref)

# new_data = {
# 'recipientContact': {
# 'name': 'Alex Hellier'
# }
# }

body.add_receipient_contact('Alex Hellier', 'alex@me.com', 'Alex S Hellier', '123455')
new_data = body.return_domestic_update_boy()
change_name = my_shipping.put_shipment(tracking_ref, new_data)
new_label = my_shipping.put_shipment_label(tracking_ref)

print(tracking_ref)
# delete_shipping = my_shipping.delete_shipment(post_shipping['completedShipments'][0]['shipmentItems'][0]['shipmentNumber'])
# print(delete_shipping)
# manifest_info = {'yourReference': '123'}
# manifest_data = my_shipping.post_manifest(manifest_info)
# print(manifest_data)
# manifest_label = my_shipping.put_manifest(manifest_batch_number=5)
# print(manifest_label)
2 changes: 1 addition & 1 deletion royal_mail_rest_api/tracking.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import requests
from royal_mail_rest_api.api import RoyalMailBaseClass


class TrackingApi(RoyalMailBaseClass):
"""
Start class for royal mail shipping api
Expand Down Expand Up @@ -85,4 +86,3 @@ def history(self, tracking_number):
print(history_tracking)
except Exception as e:
print(e)

0 comments on commit c75a820

Please sign in to comment.