REST API with Python
Implementing Complete CRUD operations in Python Without Frameworks
Note: The basic requirement to start JSON-server and Python should be installed.
Step 1:
Create a directory named 'rest' and generate two files within the directory: 'db.json' and 'rest_api_test.py'.
Utilizing db.json: A Practical Use Case for Demonstrating Python CRUD Operations Without Frameworks
Step 2:
Add some objects inside db.json as below image
Step 3:
Open the terminal and install 'requests' in Python by using the below command.
pip3 install requests
Step 4: Use the below code to test all the crud operation
# import request for perform all CRUD operation
import requests
# create header object
headers = {
"accept": "application/json",
}
# create a object or data and add into db.json
data = {
"id":"5",
"name":"Cedric",
"pass":"cd@123"
}
# CRUD all operations
# GET
response = requests.get("http://localhost:3000/data/2",headers=headers)
print(f"{response.status_code} ---> {response.json()}")
# POST
response = requests.post("http://localhost:3000/data", data = data)
print(f"{response.status_code} ---> {response.json()}")
# PUT
data = {
"name":"Sirius",
"pass":"sb@123"
}
response = requests.put("http://localhost:3000/data/2", data = data)
print(f"{response.status_code} ---> {response.json()}")
# DELETE
response = requests.put("http://localhost:3000/data/2", data = data)
print(f"{response.status_code} ---> {response.json()}")
Note: This article won't guide you through working with an actual database, but it will provide a high-level idea about CRUD operations using REST API.
Thank you for your time........
Linked In: Kumar Harsh LinkedIn
GitHub: Kumar Harsh GitHub