0

Suppose you are writing a python web client to access an API of an online supermarket. Given below are the API details.

Base URL= http://host1.open.uom.lk:8080

This is the details of API
    method      API endpoint        Description
1.  GET     /api/products/      Get all products
2.  GET     /api/products/X/    Get products with product ID X
3.  POST        /api/products/      Enter new product entry into the API server
4.  PUT     /api/products/      Update an existing product record

And the question is Write a python program to create a new product with the following information in JSON format. Print the response code of the request.

{
        "productName":"Araliya Basmathi Rice",
        "description":"White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.",
        "category":"Rice",
        "brand":"CIC",
        "expiredDate":"2023.05.04",
        "manufacturedDate":"2022.02.20",
        "batchNumber":324567,
        "unitPrice":1020,
        "quantity":200,
        "createdDate":"2022.02.24"
}

This is my code

import requests

base_url = 'http://host1.open.uom.lk:8080'
create_product_endpoint = '/api/products/'

new_product_data = {
    "productName": "Araliya Basmathi Rice",
    "description": "White Basmathi Rice imported from Pakistan. High-quality rice with extra fragrance. Organically grown.",
    "category": "Rice",
    "brand": "CIC",
    "expiredDate": "2023.05.04",
    "manufacturedDate": "2022.02.20",
    "batchNumber": 324567,
    "unitPrice": 1020,
    "quantity": 200,
    "createdDate": "2022.02.24"
}

try:
    response = requests.post(base_url + create_product_endpoint, json=new_product_data)
    response.raise_for_status()
    print("Create new product - Response Code:", response.status_code)
    print("Create new product - Response Content:", response.json())
except requests.exceptions.RequestException as err:
    print("An error occurred:", err)
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
Ahmed
  • 1

0 Answers0