<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Denis Matafonov</title>
    <description>The latest articles on DEV Community by Denis Matafonov (@dekabrsky).</description>
    <link>https://dev.to/dekabrsky</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3409874%2F49362d18-a143-4e6b-90fc-09372d3ca891.jpeg</url>
      <title>DEV Community: Denis Matafonov</title>
      <link>https://dev.to/dekabrsky</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dekabrsky"/>
    <language>en</language>
    <item>
      <title>Loading lists from the Firestore REST API: as if it were your own server</title>
      <dc:creator>Denis Matafonov</dc:creator>
      <pubDate>Sun, 10 Aug 2025 07:23:17 +0000</pubDate>
      <link>https://dev.to/dekabrsky/loading-lists-from-the-firestore-rest-api-as-if-it-were-your-own-server-532a</link>
      <guid>https://dev.to/dekabrsky/loading-lists-from-the-firestore-rest-api-as-if-it-were-your-own-server-532a</guid>
      <description>&lt;p&gt;Firebase cloud databases, and in particular Firestore, are seen as a convenient tool for building simple applications that use data from the internet. They are well-suited for quickly testing hypotheses, providing a ready-made server infrastructure and an easy-to-use SDK for client platforms. However, what if this SDK &lt;em&gt;deviates from the paradigms&lt;/em&gt; we have established in our project?&lt;/p&gt;

&lt;p&gt;Let's take a look at how you can use Firestore through the REST API. This can be done using your existing stack. For example, in my Android project, I used Retrofit, Coroutines, and more. Additionally, you can work with the RPC API as well.&lt;/p&gt;

&lt;h3&gt;
  
  
  Connection
&lt;/h3&gt;

&lt;p&gt;To work with Firestore in this way, you do not need dependencies on Firebase services. Firestore itself says that using the REST API is just in case you don't want to drag the full library. &lt;/p&gt;

&lt;p&gt;To connect to the "production" version of the databases, you can use one of the &lt;a href="https://firebase.google.com/docs/firestore/use-rest-api#authentication_and_authorization" rel="noopener noreferrer"&gt;authentication methods&lt;/a&gt;. In the test mode, API endpoints are open to everyone. &lt;/p&gt;

&lt;p&gt;The base URL becomes a string like &lt;code&gt;https://firestore.googleapis.com/v1/projects/YOUR_PROJECT_ID/databases /(default)/documents/&lt;/code&gt;, where YOUR_PROJECT_ID is the name of your project in Firebase. '/documents` is actually just one of the &lt;a href="https://firebase.google.com/docs/firestore/reference/rest" rel="noopener noreferrer"&gt;groups of methods&lt;/a&gt;, but today we are interested in it, because CRUD operations are performed through it. &lt;/p&gt;

&lt;p&gt;For requests to document collections, the names of the collections are added to this base URL, and its id is also added to access a specific element. For example, `cities/LA'.&lt;/p&gt;

&lt;h3&gt;
  
  
  Processing
&lt;/h3&gt;

&lt;p&gt;It is important that these are collections of documents, not tables. There can be any number of fields inside the elements. Therefore, we allow converters to replace missing fields with null ones and not be afraid of new fields:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Json {
    explicitNulls = false
    ignoreUnknownKeys = true
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you can (almost) feel free to create new documents with a new structure - without migrations and other adventures. &lt;/p&gt;

&lt;p&gt;When requesting a collection, we will receive the following response:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F92hg6qnpgg4cxy2idun4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F92hg6qnpgg4cxy2idun4.png" alt="Response example Firestore REST API" width="800" height="273"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In addition to the collection itself (documents), other fields may be received in the object, for example, a pagination token. Please note that the fields of our records come in wrappers corresponding to their types, which is not very convenient for me.&lt;/p&gt;

&lt;h3&gt;
  
  
  Setting up queries
&lt;/h3&gt;

&lt;p&gt;In the example above, we are implementing a news feed. The news should be sorted by the time they were created, with the most recent ones at the top. By default, Firebase Firestore returns records in order of their id. While it would be possible to number them manually, we will let the ids stay automatic. We can assume that we can use the "createTime" field provided by Firebase in the document.&lt;/p&gt;

&lt;p&gt;There are two things to note here. The good news is that we can actually specify an "OrderBy" query parameter to sort our records. However, the bad news is that this can only be done using existing fields. Therefore, we need to add "createTime" to our fields ourselves.&lt;/p&gt;

&lt;p&gt;To do this, we use the following parameter: &lt;code&gt;@Query("orderBy") orderBy: String = "createTime desc".&lt;/code&gt; Note that the sorting direction is not a separate parameter, but is included with the field.&lt;/p&gt;

&lt;h3&gt;
  
  
  Pagination
&lt;/h3&gt;

&lt;p&gt;Firestore allows you to upload data in batches. To do so, you can add the query parameter &lt;code&gt;pageSize&lt;/code&gt; to specify the number of items in each batch, and &lt;code&gt;pageToken&lt;/code&gt; to get the next page of results. This allows you to use pagination tools like Paging3, which have their own advantages.&lt;/p&gt;

&lt;h2&gt;
  
  
  Overall
&lt;/h2&gt;

&lt;p&gt;Using Firestore via its REST API doesn't limit you from using its features. In fact, it can be integrated with a standard networking stack. This might be an additional reason to consider using it for your product or learning project.&lt;/p&gt;

</description>
      <category>firebase</category>
      <category>firestore</category>
      <category>android</category>
      <category>mobile</category>
    </item>
    <item>
      <title>Грузим списки с Firestore REST API: как будто свой сервер</title>
      <dc:creator>Denis Matafonov</dc:creator>
      <pubDate>Sat, 09 Aug 2025 19:15:29 +0000</pubDate>
      <link>https://dev.to/dekabrsky/gruzim-spiski-s-firestore-rest-api-kak-budto-svoi-siervier-2nif</link>
      <guid>https://dev.to/dekabrsky/gruzim-spiski-s-firestore-rest-api-kak-budto-svoi-siervier-2nif</guid>
      <description>&lt;p&gt;en version: &lt;a href="https://dev.to/dekabrsky/loading-lists-from-the-firestore-rest-api-as-if-it-were-your-own-server-532a"&gt;https://dev.to/dekabrsky/loading-lists-from-the-firestore-rest-api-as-if-it-were-your-own-server-532a&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Облачные базы данных Firebase, в частности  Firestore, принято считать удобным инструментом для реализации простых приложений с данными из сети, они хорошо подходят для быстрой проверки гипотез, предоставляя нам готовую серверную инфраструктуру и &lt;em&gt;удобный&lt;/em&gt; SDK на платформах-клиентах. Но что если этот SDK для нас - отклонение от принятых в проекте парадигм? &lt;/p&gt;

&lt;p&gt;Давайте посмотрим, как можно использовать Firestore REST API. Его можно использовать с привычным вам стеком, например, в моем проекте на Android это были Retrofit, корутины и так далее. Кстати, можно работать и с RPC API.&lt;/p&gt;

&lt;h3&gt;
  
  
  Подключение
&lt;/h3&gt;

&lt;p&gt;Для такой работы с Firestore не нужны зависимости на сервисы Firebase. Сами Firestore как раз и говорят, что использование REST API - как раз на тот случай, если вы не хотите тащить полную библиотеку. &lt;/p&gt;

&lt;p&gt;Для подключения к "продовой" версии баз можно воспользоваться одним из &lt;a href="https://firebase.google.com/docs/firestore/use-rest-api#authentication_and_authorization" rel="noopener noreferrer"&gt;способов аутентификации&lt;/a&gt;. В тестовом режиме эндпойнты API открыты всем. &lt;/p&gt;

&lt;p&gt;Базовым URL становится строка вида &lt;code&gt;https://firestore.googleapis.com/v1/projects/YOUR_PROJECT_ID/databases/(default)/documents/&lt;/code&gt;, где YOUR_PROJECT_ID - имя вашего проекта в Firebase. &lt;code&gt;/documents&lt;/code&gt;, на самом деле, только одна из &lt;a href="https://firebase.google.com/docs/firestore/reference/rest" rel="noopener noreferrer"&gt;групп методов&lt;/a&gt;, но сегодня нас интересует именно она, ведь через нее выполняются CRUD-операции. &lt;/p&gt;

&lt;p&gt;Для запросов к коллекциям документов к этому базовому URL добавляются названия коллекций, для доступа к конкретному элементу - еще и его id. Например, &lt;code&gt;cities/LA&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Обработка
&lt;/h3&gt;

&lt;p&gt;Важно, что это именно коллекции документов, а не таблицы. Внутри элементов могут быть какой угодно состав полей. Поэтому разрешаем конвертерам подменять отсутствующие поля null'ами и не бояться новых полей:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Json {
    explicitNulls = false
    ignoreUnknownKeys = true
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Теперь можно (почти) не стесняться создавать новые документы с новой структурой - без миграций и прочих приключений. &lt;/p&gt;

&lt;p&gt;При запросе коллекции нам придет следующий ответ:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F92hg6qnpgg4cxy2idun4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F92hg6qnpgg4cxy2idun4.png" alt="Пример ответа Firestore REST API" width="800" height="273"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Кроме самой коллекции (documents), в объекте могут приходить другие поля, например токен для пагинации. Обращаем внимание, что поля наших записей приходят в обертках, соответствующих их типам - не очень удобно.  &lt;/p&gt;

&lt;h3&gt;
  
  
  Настраиваем запросы
&lt;/h3&gt;

&lt;p&gt;В примере выше я реализую новости. Новости должны сортироваться по убыванию времени создания - новые в начале списка. По умолчанию Firestore отдает записи отсортированными по id. Можно было бы конечно им давать номера по порядку, но пускай id остаются автоматическими. Логично предположить, что можно воспользоваться предоставляемым самим Firestore полем createTime в документе. &lt;/p&gt;

&lt;p&gt;Тут две новости, хорошая и плохая. Хорошая - действительно можно указать query-параметр orderBy и отсортировать наши записи. Плохая - это можно сделать только по полям из fields. Соответственно, нужно добавлять в наши поля createTime своими силами. &lt;/p&gt;

&lt;p&gt;Параметр получается следующий: &lt;code&gt;@Query("orderBy") orderBy: String = "createTime desc",&lt;/code&gt;. Да, направление сортировки - не отдельный параметр, а живет вместе с полем. &lt;/p&gt;

&lt;h3&gt;
  
  
  Пагинация
&lt;/h3&gt;

&lt;p&gt;API Firestore позволяет загружать данные порциями, для этого следует добавить в запрос query-параметры размера порции &lt;code&gt;pageSize&lt;/code&gt; и токен следующей страницы, полученный из страницы предыдущей - &lt;code&gt;pageToken&lt;/code&gt;. Теперь можно использовать, например, Paging3 с его преимуществами.&lt;/p&gt;

&lt;h2&gt;
  
  
  Итого
&lt;/h2&gt;

&lt;p&gt;Использование Firestore через его REST API не ограничивает нас в использовании его функциональности, при этом становится возможным использовать его со стандартным стеком, связанным с работой с сетью. Возможно, это лишний повод рассмотреть его в своем продуктовом или учебном проекте. &lt;/p&gt;

</description>
      <category>mobile</category>
      <category>firebase</category>
      <category>android</category>
      <category>firestore</category>
    </item>
  </channel>
</rss>
