# GraphQL vs REST

{% embed url="<https://graphql.github.io/swapi-graphql/>" %}
GraphQL Playground
{% endembed %}

## 🆚 Comparison

| Aspect                 | GraphQL                                      | REST                                                  |
| ---------------------- | -------------------------------------------- | ----------------------------------------------------- |
| Data Fetching          | Single request to fetch data                 | Multiple requests to different endpoints              |
| API Versioning         | No versioning needed, evolves through schema | Versioning typically required                         |
| Flexibility            | Clients can request exactly what they need   | Fixed endpoints with defined responses                |
| Over-fetching          | Avoids over-fetching by selecting fields     | Often results in over-fetching                        |
| Under-fetching         | Avoids under-fetching by nesting queries     | Can result in under-fetching, requiring more requests |
| Schema and Type System | Strongly typed schema                        | No inherent type system                               |
| Performance            | Can be more efficient with fewer requests    | Can be less efficient with multiple endpoints         |
| Learning Curve         | Steeper learning curve                       | More straightforward and widely understood            |
| Error Handling         | Standardized error responses                 | Varies by implementation                              |
| Caching                | More complex due to single endpoint          | Simplified caching with HTTP protocols                |
| Batching and Caching   | Supports batching and deduplication          | Requires custom solutions                             |
| Tooling and Ecosystem  | Growing tooling and libraries                | Mature and extensive tooling and libraries            |
| Security               | Requires careful implementation of security  | Mature security practices                             |
| Real-time Updates      | Supports subscriptions for real-time updates | Typically relies on WebSockets or polling             |
| Documentation          | Self-documenting with introspection          | Requires separate documentation                       |
| Deployment Complexity  | Can be complex due to schema stitching       | Typically simpler and well understood                 |

## 🅰️ GraphQL

{% hint style="info" %}
**Data fetching** : โดย client สามารถร้องขอข้อมูลที่ต้องการ เพียงระบุ fields ที่ต้องการในข้อมูล และ server จะส่งข้อมูลกลับเฉพาะ fields นั้น ซึ่งช่วยลดการโหลดข้อมูลที่ไม่จำเป็นตอน response

**Writing and Maintenance** : ไม่จำเป็นต้องสร้าง endpoint ใหม่เพื่อ actions แต่จะใช้ schema ที่ถูกกำหนดไว้ล่วงหน้า (predefined schema) และ resolver functions ที่สอดคล้องกับ schema เพื่อจัดการกับข้อมูล ซึ่งสามารถขยาย schema ได้ตามความต้องการ

**Error handling** : มี error handling ที่ยืดหยุ่นกว่า ซึ่งสามารถรวมข้อผิดพลาดหลาย ๆ อย่างได้ใน response เดียว และ client สามารถระบุ errors ที่ต้องการจาก query นั้น ๆ

**Performance** : สำหรับแอปพลิเคชันที่ต้องการดึงข้อมูลหลาย ๆ ชุดพร้อม ๆ กัน GraphQL อาจช่วยลดจำนวน request ที่ต้องใช้งานลงไป และลดการโหลดข้อมูลที่ไม่จำเป็น ซึ่งอาจช่วยเพิ่มประสิทธิภาพในบางกรณีได้
{% endhint %}

{% tabs %}
{% tab title="Basic" %}

```graphql
fragment FilmInfo on Film {
  title
  director
  producers
  releaseDate
}

query Films {
  allFilms {
    totalCount
    films {
      created
      releaseDate
      openingCrawl
      ...FilmInfo
    }
  }
}
```

{% endtab %}

{% tab title="Object Type Pagination" %}

```graphql
fragment FilmInfo on Film {
  title
  director
  producers
  releaseDate
}

query Films($firstN: Int, $afterCursor: String) {
  allFilms(first: $firstN, after: $afterCursor) {
    totalCount
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
    films {
      ...FilmInfo
    }
  }
}
```

{% code title="Variables" %}

```json
{
  "firstN": 1,
  "afterCursor": "YXJyYXljb25uZWN0aW9uOjA="
}
```

{% endcode %}
{% endtab %}

{% tab title="Edges Pagination" %}

```graphql
fragment FilmInfo on Film {
  title
  director
  producers
  releaseDate
}

query Films($firstN: Int, $afterCursor: String) {
  allFilms(first: $firstN, after: $afterCursor) {
    totalCount
    pageInfo {
      hasNextPage
      hasPreviousPage
      startCursor
      endCursor
    }
    edges {
      cursor
      node {
        ...FilmInfo
      }      
    }
  }
}
```

{% code title="variables" %}

```json
{
  "firstN": 1,
  "afterCursor": "YXJyYXljb25uZWN0aW9uOjA="
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

## 🅱️ REST

{% hint style="info" %}
**Data fetching** : ข้อมูลถูกแบ่งออกเป็นแต่ละ endpoint ที่สามารถถูกเรียกใช้งานได้โดยแต่ละ endpoint จะส่งคืนข้อมูลที่ถูกกำหนดไว้ล่วงหน้า (predefined) โดย Client จะต้องเรียก endpoint ต่าง ๆ เพื่อรับข้อมูลที่ต้องการ

**Writing and Maintenance** : การออกแบบ REST API มักจะแยก endpoint ตาม (actions) และ (data) ซึ่งอาจทำให้มีจำนวน endpoint มากขึ้นเมื่อมีการเพิ่มฟังก์ชันใหม่ ๆ ในระบบ

**Error handling** : มักจะใช้ HTTP status codes เพื่อระบุสถานะของการทำงาน เช่น 200 OK, 404 Not Found, 500 Internal Server Error เป็นต้น

**Performance** : ในบางกรณี REST API อาจมีประสิทธิภาพที่ดีกว่า GraphQL เนื่องจาก REST API ส่งข้อมูลที่ถูกกำหนดไว้ล่วงหน้า และไม่มีความซับซ้อนในการประมวลผล query
{% endhint %}
