GraphQL vs REST: обзор

Phil Sturgeon, “GraphQL vs REST: Overview”, public translation into English from English More about this translation.

Translate into another language.

Participants

Big_Shark 82 points
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: previous Ctrl next next untranslated
1 2 3 4 5 6 7 8 9 10

Is the API More Than Data Transfer?

One of the most common tasks REST APIs provide is CRUD via JSON, but it can do plenty more than that, such as file uploads.

Uploading an image in the HTTP body can look a little something like this:

POST /avatars HTTP/1.1

Host: localhost:3000

Content-Type: image/jpeg

Content-Length: 284

raw image content

Leveraging a cool part of HTTP (and therefore REST), API developers can support application/json requests on the same endpoint to handle the upload slightly differently, and offer URL-based uploads too:

POST /avatars HTTP/1.1

Host: localhost:3000

Content-Type: application/json

{

"image_url" : "https://example.org/pic.png"

}

Generally the APIs I have worked on have enjoyed both, which is super handy as iOS often sends photos directly from local files, and web clients often send a URL to the user's Facebook display picture.

If we were talking about uploading videos or other large files, I would (as this article suggests) switch to another approach and have a dedicated service which handles the upload, leaving the main API to only accept metadata; title, description, tags, etc.

This is the approach you are forced to take with GraphQL, because you can only speak to GraphQL in terms of fields:

POST /graphql HTTP/1.1

Host: localhost:3000

Content-Type: application/graphql

mutation addAvatar {

addAvatarFromUrl(image_url: "https://example.org/pic.png") {

id,

image_url

}

}

Some will argue that this is more "clean", and it is, it's very clean, but being forced to create another service is overkill for smaller images, especially early on. Another approach is to upload directly to Amazon S3, forcing a dependency on clients and potentially letting your tokens leak, or… use multipart uploads, which are a super hacky approach that depends on if the server and various clients can even support it.

This is one area where REST holds strong. Some would say that REST handling CRUD and arbitrary stuff is confusing, but this is a core tenant of what makes REST so useful. A REST API can do anything, not just send fields backwards and forwards - even if that is how REST is often used.

Pages: previous Ctrl next next untranslated
1 2 3 4 5 6 7 8 9 10