Sunday 10 December 2017

REST API endpoints with Firestore

Firestore is the new database cloud service from Google to support web/mobile development. It was launched in October this year.

If you have google account you can create your own database for your applications.

One interesting thing you can do it is to have endpoints to access to your firestore collections (tables) using REST API.

I will summarize how you can have the endpoints for a CRUD application using one collection in firestore.

First step is to create a collection in firestore that I will call 'tasks'
This collection will have 2 fields: title and description.




Get list of records:
GET
https://firestore.googleapis.com/v1beta1/projects/YOUR_PROJECT_ID/databases/(default)/documents/COLLECTION_NAME
Example:
GET
https://firestore.googleapis.com/v1beta1/projects/myproject/databases/(default)/documents/tasks

The response will have this format:
{
    "documents": [
        {
            "name": "projects/angular-task-e7f39/databases/(default)/documents/tasks/Cw36XeLhvf9widHiatQG",
            "fields": {
                "description": {
                    "stringValue": "Task1"
                },
                "title": {
                    "stringValue": "My first task"
                }
            },
            "createTime": "2017-12-04T23:04:03.933099Z",
            "updateTime": "2017-12-04T23:04:03.933099Z"
        }
   ]
}

Get one record by Id:
GET

https://firestore.googleapis.com/v1beta1/projects/YOUR_PROJECT_ID/databases/(default)/documents/COLLECTION_NAME/ID

Example:
GET
https://firestore.googleapis.com/v1beta1/projects/myproject/databases/(default)/documents/tasks/ Cw36XeLhvf9widHiatQG


The response will have this format:

{
    "name": "projects/angular-task-e7f39/databases/(default)/documents/tasks/Cw36XeLhvf9widHiatQG",
    "fields": {
        "title": {
            "stringValue": "Task1"
        },
        "description": {
            "stringValue": "My first task"
        }
    },
    "createTime": "2017-12-04T23:04:03.933099Z",
    "updateTime": "2017-12-04T23:04:03.933099Z"
}


Create a new record:
POST
https://firestore.googleapis.com/v1beta1/projects/YOUR_PROJECT_ID/databases/(default)/documents/COLLECTION_NAME
Example:
POST
https://firestore.googleapis.com/v1beta1/projects/myproject/databases/(default)/documents/tasks

Request body:
{  
   "fields":{  
      "title":{  
         "stringValue":"task2"
      },
      "description":{  
         "stringValue":"My second task"
      }
   }
}

Delete one record by Id:

DELETE
https://firestore.googleapis.com/v1beta1/projects/YOUR_PROJECT_ID/databases/(default)/documents/COLLECTION_NAME/ID

Example:
DELETE
https://firestore.googleapis.com/v1beta1/projects/myproject/databases/(default)/documents/tasks/Cw36XeLhvf9widHiatQG


No comments:

Post a Comment