REST API Tutorial with RESTHeart
This tutorial introduces RESTHeart’s MongoDB REST API through simple examples. You’ll learn the basics of querying and modifying data using standard HTTP methods.
🔧 Configuration
Create and populate the inventory
collection
cURL
curl -i -X PUT [INSTANCE-URL]/inventory \
-H "Authorization: Basic [BASIC-AUTH]"
curl -i -X POST [INSTANCE-URL]/inventory \
-H "Authorization: Basic [BASIC-AUTH]" \
-H "Content-Type: application/json" \
-d '[
{ "item": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" },
{ "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" },
{ "item": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" },
{ "item": "planner", "qty": 75, "size": { "h": 22.85, "w": 30, "uom": "cm" }, "status": "D" },
{ "item": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }
]'
HTTPie
http PUT [INSTANCE-URL]/inventory Authorization:"Basic [BASIC-AUTH]"
echo '[
{ "item": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" },
{ "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" },
{ "item": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" },
{ "item": "planner", "qty": 75, "size": { "h": 22.85, "w": 30, "uom": "cm" }, "status": "D" },
{ "item": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }
]' | http [INSTANCE-URL]/inventory Authorization:"Basic [BASIC-AUTH]"
JavaScript
// Create collection
fetch("http://localhost:8080/inventory", {
method: "PUT",
headers: {
Authorization: "Basic YWRtaW46c2VjcmV0",
},
}).then((response) => {
if (response.ok) {
console.log("Collection created successfully");
const data = [
{
item: "journal",
qty: 25,
size: { h: 14, w: 21, uom: "cm" },
status: "A",
},
{
item: "notebook",
qty: 50,
size: { h: 8.5, w: 11, uom: "in" },
status: "A",
},
{
item: "paper",
qty: 100,
size: { h: 8.5, w: 11, uom: "in" },
status: "D",
},
{
item: "planner",
qty: 75,
size: { h: 22.85, w: 30, uom: "cm" },
status: "D",
},
{
item: "postcard",
qty: 45,
size: { h: 10, w: 15.25, uom: "cm" },
status: "A",
},
];
// Insert documents
fetch("http://localhost:8080/inventory", {
method: "POST",
body: JSON.stringify(data),
headers: {
Authorization: "Basic YWRtaW46c2VjcmV0",
"Content-Type": "application/json",
},
})
.then((response) => {
if (response.ok) {
console.log("Documents inserted successfully");
} else {
console.error("Failed to insert documents:", response.status);
}
})
.catch((error) => console.error("Error:", error));
} else {
console.error("Failed to create collection:", response.status);
}
})
.catch((error) => console.error("Error:", error));
Retrieving documents
To retrieve all documents from a collection, send a GET
request:
cURL
curl -i -X GET [INSTANCE-URL]/inventory \
-H "Authorization: Basic [BASIC-AUTH]"
HTTPie
http GET [INSTANCE-URL]/inventory \
Authorization:"Basic [BASIC-AUTH]"
JavaScript
fetch('[INSTANCE-URL]/inventory', {
headers: {
'Authorization': 'Basic [BASIC-AUTH]'
}
})
.then(response => response.json())
.then(data => {
console.log('Retrieved documents:', data);
})
.catch(error => console.error('Error:', error));
The response contains an array of all documents in the collection (limited by the default page size):
[
{
"_id": {
"$oid": "5d0b3dbc2ec9ff0d92ddc2aa"
},
"_etag": {
"$oid": "5d0b3dbc2ec9ff0d92ddc2a5"
},
"item": "postcard",
"qty": 45,
"size": {
"h": 10,
"w": 15.25,
"uom": "cm"
},
"status": "A"
},
{
"_id": {
"$oid": "5d0b3dbc2ec9ff0d92ddc2a9"
},
"_etag": {
"$oid": "5d0b3dbc2ec9ff0d92ddc2a5"
},
"item": "planner",
"qty": 75,
"size": {
"h": 22.85,
"w": 30,
"uom": "cm"
},
"status": "D"
}
]
Filtering documents
You can filter documents using the filter
query parameter with MongoDB query syntax:
cURL
curl -i -X GET "[INSTANCE-URL]/inventory" \
-H "Authorization: Basic [BASIC-AUTH]" \
--data-urlencode 'filter={"qty":{"$gt":75}}'
HTTPie
http GET "[INSTANCE-URL]/inventory" \
Authorization:"Basic [BASIC-AUTH]" \
filter=="{\"qty\":{\"\$gt\":75}}"
JavaScript
const filter = encodeURIComponent('{"qty":{"$gt":75}}');
fetch(`[INSTANCE-URL]/inventory?filter=${filter}`, {
headers: {
'Authorization': 'Basic [BASIC-AUTH]'
}
})
.then(response => response.json())
.then(data => {
console.log('Filtered documents:', data);
})
.catch(error => console.error('Error:', error));
This returns only documents where the quantity is greater than 75:
[
{
"_id": {
"$oid": "5d0b3dbc2ec9ff0d92ddc2a8"
},
"_etag": {
"$oid": "5d0b3dbc2ec9ff0d92ddc2a5"
},
"item": "paper",
"qty": 100,
"size": {
"h": 8.5,
"w": 11,
"uom": "in"
},
"status": "D"
}
]
Creating documents
To create a new document, use the POST
method with a JSON body:
cURL
curl -i -X POST [INSTANCE-URL]/inventory \
-H "Authorization: Basic [BASIC-AUTH]" \
-H "Content-Type: application/json" \
-d '{"item": "newItem", "qty": 10, "size": { "h": 2, "w": 4, "uom": "cm" }, "status": "C"}'
HTTPie
http POST [INSTANCE-URL]/inventory \
Authorization:"Basic [BASIC-AUTH]" \
item="newItem" qty:=10 size:='{"h": 2, "w": 4, "uom": "cm"}' \
status="C"
JavaScript
fetch('[INSTANCE-URL]/inventory', {
method: 'POST',
headers: {
'Authorization': 'Basic [BASIC-AUTH]',
'Content-Type': 'application/json'
},
body: JSON.stringify({
item: 'newItem',
qty: 10,
size: { h: 2, w: 4, uom: 'cm' },
status: 'C'
})
})
.then(response => {
if (response.ok) {
console.log('Document created successfully');
console.log('Location:', response.headers.get('Location'));
} else {
console.error('Failed to create document:', response.status);
}
})
.catch(error => console.error('Error:', error));
The server responds with headers including a Location
that points to the newly created document:
HTTP/1.1 201 Created
ETag: 5d0b47422ec9ff0d92ddc2ad
Location: http://localhost:8080/inventory/5d0b47425beb2029a8d1bc72
Content-Type: application/json
Tip
|
The Location header contains the URI of the new document. You can use this URI to access the document directly.
|
Creating documents with a specified ID
You can create a document with a specific ID using the PUT
method with the ?wm=upsert
query parameter:
cURL
curl -i -X PUT [INSTANCE-URL]/inventory/newDocument?wm=upsert \
-H "Authorization: Basic [BASIC-AUTH]" \
-H "Content-Type: application/json" \
-d '{ "item": "yetAnotherItem", "qty": 90, "size": { "h": 3, "w": 4, "uom": "cm" }, "status": "C" }'
HTTPie
http PUT [INSTANCE-URL]/inventory/newDocument \
Authorization:"Basic [BASIC-AUTH]" \
wm==upsert \
item="yetAnotherItem" qty:=90 size:='{"h": 3, "w": 4, "uom": "cm"}' \
status="C"
JavaScript
fetch('[INSTANCE-URL]/inventory/newDocument?wm=upsert', {
method: 'PUT',
headers: {
'Authorization': 'Basic [BASIC-AUTH]',
'Content-Type': 'application/json'
},
body: JSON.stringify({
item: 'yetAnotherItem',
qty: 90,
size: { h: 3, w: 4, uom: 'cm' },
status: 'C'
})
})
.then(response => {
if (response.ok) {
console.log('Document created/updated successfully');
} else {
console.error('Failed to create/update document:', response.status);
}
})
.catch(error => console.error('Error:', error));
Note
|
The wm=upsert parameter is needed because the default write mode for PUT is "update". The "upsert" mode creates the document if it doesn’t exist.
|
Updating documents
To modify specific properties of an existing document, use the PATCH
method:
cURL
curl -i -X PATCH [INSTANCE-URL]/inventory/newDocument \
-H "Authorization: Basic [BASIC-AUTH]" \
-H "Content-Type: application/json" \
-d '{ "qty": 40, "status": "A", "newProperty": "value" }'
HTTPie
http PATCH [INSTANCE-URL]/inventory/newDocument \
Authorization:"Basic [BASIC-AUTH]" \
qty:=40 status="A" newProperty="value"
JavaScript
fetch('[INSTANCE-URL]/inventory/newDocument', {
method: 'PATCH',
headers: {
'Authorization': 'Basic [BASIC-AUTH]',
'Content-Type': 'application/json'
},
body: JSON.stringify({
qty: 40,
status: 'A',
newProperty: 'value'
})
})
.then(response => {
if (response.ok) {
console.log('Document updated successfully');
} else {
console.error('Failed to update document:', response.status);
}
})
.catch(error => console.error('Error:', error));
This updates only the specified fields and adds new fields:
{
"_id": "newDocument",
"item": "yetAnotherItem",
"qty": 40,
"size": {
"h": 3,
"w": 4,
"uom": "cm"
},
"status": "A",
"_etag": {
"$oid": "5d0b4b9e2ec9ff0d92ddc2af"
},
"newProperty": "value"
}
Deleting documents
To delete a document, use the DELETE
method:
cURL
curl -i -X DELETE [INSTANCE-URL]/inventory/newDocument \
-H "Authorization: Basic [BASIC-AUTH]"
HTTPie
http DELETE [INSTANCE-URL]/inventory/newDocument \
Authorization:"Basic [BASIC-AUTH]"
JavaScript
fetch('[INSTANCE-URL]/inventory/newDocument', {
method: 'DELETE',
headers: {
'Authorization': 'Basic [BASIC-AUTH]'
}
})
.then(response => {
if (response.ok) {
console.log('Document deleted successfully');
} else {
console.error('Failed to delete document:', response.status);
}
})
.catch(error => console.error('Error:', error));
A successful deletion returns a 204 No Content
status.
Next steps
Now that you understand the basics, explore more advanced features:
-
Read Documents - Learn about pagination, sorting, and projection
-
Write Documents - Learn about bulk operations and update operators
-
Aggregations - Run MongoDB aggregation pipelines via REST