0
0
Drone-programmingHow-ToBeginner · 4 min read

How to Use REST API in IoT: Simple Guide for Beginners

To use a REST API in IoT, your device sends HTTP requests like GET or POST to a server URL to exchange data. This lets IoT devices communicate with cloud services or other devices using simple web protocols.
📐

Syntax

A REST API call in IoT typically uses HTTP methods to interact with resources:

  • GET: Retrieve data from the server.
  • POST: Send new data to the server.
  • PUT: Update existing data.
  • DELETE: Remove data.

The request includes a URL endpoint, headers (like content type), and optionally a body with data.

http
GET /sensor/data HTTP/1.1
Host: api.example.com
Content-Type: application/json

POST /sensor/data HTTP/1.1
Host: api.example.com
Content-Type: application/json

{"temperature": 22.5, "humidity": 60}
💻

Example

This example shows an IoT device sending temperature data to a REST API using Python's requests library.

python
import requests

url = 'https://api.example.com/sensor/data'
data = {"temperature": 22.5, "humidity": 60}
headers = {'Content-Type': 'application/json'}

response = requests.post(url, json=data, headers=headers)
print('Status code:', response.status_code)
print('Response:', response.json())
Output
Status code: 201 Response: {"message": "Data received successfully"}
⚠️

Common Pitfalls

Common mistakes when using REST API in IoT include:

  • Not setting the correct Content-Type header, causing the server to reject data.
  • Ignoring response status codes, missing errors like 400 or 500.
  • Sending data in wrong format (e.g., plain text instead of JSON).
  • Not handling network failures or retries.
python
Wrong way:
import requests
url = 'https://api.example.com/sensor/data'
data = 'temperature=22.5&humidity=60'
response = requests.post(url, data=data)  # Missing JSON and headers

Right way:
import requests
url = 'https://api.example.com/sensor/data'
data = {"temperature": 22.5, "humidity": 60}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, json=data, headers=headers)
📊

Quick Reference

HTTP MethodPurposeExample Usage
GETRetrieve dataGET /sensor/data
POSTSend new dataPOST /sensor/data with JSON body
PUTUpdate dataPUT /sensor/data/123 with JSON body
DELETERemove dataDELETE /sensor/data/123

Key Takeaways

Use HTTP methods like GET and POST to communicate with REST APIs in IoT devices.
Always set the Content-Type header to application/json when sending JSON data.
Check server response codes to handle errors properly.
Send data in the correct format and handle network issues gracefully.
REST APIs enable simple, standard communication between IoT devices and servers.