makes   1104

« earlier    

REST vs GraphQL APIs, the Good, the Bad, the Ugly | Moesif’s Musings on Software
REST vs GraphQL APIs, the Good, the Bad, the Ugly
GraphQL adoption is exploding, but should you migrate to GraphQL?
February 27, 2018
Since being introduced by Facebook, GraphQL has taken the API world by storm as an alternative to REST APIs. GraphQL fixes many problems that API developers and users have found with RESTful architecture. However, it also introduces a new set of challenges which need to be evaluated. Because GraphQL is not simply a evolutionary replacement for REST, this post will deep dive into the pros and cons of each and when GraphQL makes sense for your application.
History
Before RESTful APIs, we had RPC, SOAP, CORBA, and other less open protocols. Many pre-REST APIs required complex client libraries to serialize/deserialize the payload over the wire. A fundamental difference compared to today’s RESTful APIs, is that SOAP is strongly typed using formal contracts via WSDL (Web Services Description Language). This could wreck havoc on interoperability since even removing a 32-bit integer restriction to accepting a 64-bit long meant breaking upstream clients. SOAP is not an architecture, but a full protocol implementation consisting of security, error handling, ACID transactions, etc Some of the complexity is due to many abstraction layers baked into SOAP. For example, SOAP is able to run on HTTP, TCP, UDP, etc. While the protocol implementation afforded much abstraction, the application and data layer’s rigid contract between the client and server created a tight coupling between the two.
RESTful architecture was introduced in 2000 as a much simpler way to enable machine to machine communication using only the ubiquitous HTTP protocol without additional layers in a stateless and type free way. This enabled systems to be loosely coupled and more forgiving to contract changes between systems such as between companies.
REST today
REST APIs have become the de facto standard for companies deploying APIs and launching developer platforms. The beauty of REST is that a developer working with someone else’s API doesn’t need any special initialization or libraries. Requests can be simply sent via common software like cURL and web browsers.
REST uses the standard CRUD HTTP Verbs (GET, POST, PUT, DELETE) and leverages HTTP conventions and centered around data resources (HTTP URIs) rather than attempting to fight HTTP. Thus an e-commerce with a resource api.acmestore.com/items can behave similar to a bank with a resource api.examplebank.com/deposits. Both would probably need CRUD operations on that resource and prefer to cache queries (i.e. both GET api.acmestore.com/items and GET api.examplebank.com/transactions would be cached). 3rd party developers to a new API need to only reason about the data model and leave the rest to HTTP convention rather than digging deep into thousands of operations. In other words, REST is much tighter coupled to HTTP and CRUD compared to SOAP, but provides loose data contracts.
Problems with REST
As more variety of APIs are placed in production use and scaled to extreme levels, certain problems in RESTful architecture transpired. You could even say GraphQL is between SOAP and REST taking pieces from each.
Server driven selection
In RESTful APIs, the server creates the representation of a resource to be responded back to a client.
However, what if the client wants something specific such as return the names of friends of friends of a user where their job is engineer.
With REST, you might have something like:
GET api.example.com/users/123?include=friend.friend.name&friend.friend.ocupation=engineer
GraphQL allows you to represent this query in a cleaner way:
{
user(id: 123) {
friends {
friends(job: "engineer") {
name
}
}
}
}
Fetching multiple resources
One of the main benefits of GraphQL is to make APIs less chatty. Many of us have seen an API where we first have to GET /user first and then fetch each friend individually via GET /user/:id/friend/:id endpoint, this can result in N+1 queries and is a will known performance issue in API and database queries. In other words, RESTful API calls are chained on the client before the final representation can be formed for display. GraphQL can reduce this by enabling the server to aggregate the data for the client in a single query.
More in depth analytics
While API analytics is also a negative for GraphQL apis since there is very little tooling out there. The tools that do support GraphQL APIs can provide much more insights into queries than RESTful APIs.
Problems with GraphQL
Caching
Caching is built into in the HTTP specification which RESTful APIs are able to leverage. GET vs POST semantics related to caching are well defined enabling browser caches, intermediate proxies, and server frameworks to follow. The following guidelines can be followed:
GET requests can be cached
GET requests can stay in browser history
GET requests can be bookmarked
GET requests are idempotent
GraphQL doesn’t follow the HTTP spec for caching and instead uses a single endpoint. Thus, it’s up to the developer to ensure caching is implemented correctly for non-mutable queries that can be cached. The correct key has to be used for the cache which may include inspecting the body contents.
While you can use tools like Relay or Dataloader that understands GraphQL semantics, that still doesn’t cover things like browser and mobile caching.
Diminishes shared nothing architecture
The beauty of RESTful APIs is that they complement shared nothing architecture well. For example, Moesif has a api.moesif.com/v1/search endpoint and a api.moesif.com/v1/alerting endpoint. Publicly, those two endpoints simply look like two different REST resources. Internally though, they point to two different microservices on isolated compute clusters. The search service is written in Scala and the alerting service is written in NodeJS. The complexity in routing HTTP requests via host or URL is much lower than inspecting a GraphQL query and performing multiple joins.
Exposed for arbitrary requests
While a main benefit of GraphQL is to enable clients to query for just the data they need, this can also be problematic especially for open APIs where an organization cannot control 3rd party client query behavior. Great care has to be taken to ensure GraphQL queries don’t result in expensive join queries that can bring down server performance or even DDoS the server. RESTful APIs can be constrained to match data model and indexing used.
Rigidness of queries
GraphQL removes the ability for custom query DSLs or side effect operations on top of an API. For example, the Elasticsearch API is RESTful, but also has a very powerful Elasticsearch DSL to perform advanced aggregations and metric calculations. Such aggregation queries may be harder to model within the GraphQL language.
Non existent monitoring
RESTful APIs have the benefit of following the HTTP spec with regards to resources just like a website. This enables many tools to probe a URL such as api.moesif.com/health which would return 5xx if not OK. For GraphQL APIs, you may not be able to leverage such tools unless you support placing the query as a URL parameter as most ping tools don’t support HTTP and request bodies.
Besides ping services, there are very few SaaS or open source tools that support API analytics or deeper analysis of your API calls. Client errors are presented as a 200 OK in a GraphQL API. Existing tools that expect 400 errors will not work so you may miss errors happening on your API. Yet at the same time, more flexibility given to the client requires even more tools to catch and understand problems with your API.
Conclusion
GraphQL APIs can be exciting new technology, but it is important to understand the tradeoffs before making such architectural decisions. Some APIs such as those with very few entities and relationships across entities like analytics APIs may not be suited for GraphQL. Whereas applications with many different domain objects like e-commerce where you have items, users, orders, payments, and so on may be able to leverage GraphQL much more.
In  fact_  GraphQL  vs  REST  is  like  comparing  SQL  technologies  vs  noSQL.  There  are  certain  applications  where  it  makes  sense  to  model  complex  entities  a  SQL  Db.  Whereas  other  apps  that  only  have  “messages”  as  high  volume  chat  apps  or  analytics  APIs  where  the  only  entity  is  an  “event”  may  be  more  suited  using  something  like  Cassandra.  from iphone
12 days ago by heapdump
The New Fujifilm Instax SQ6 Makes Analog Square Again
Most would associate the ubiquitous square format to Instagram’s influence today. Most other cameras produce some sort of a rectangular photograph. Almost all digital cameras today adopt a 3:2 aspect ratio, as did their analogue forebears on 35mm film. The 1:1 format is an oddity, observed only on medium format cameras like the Hasselblad, and the iconic...

The post The New Fujifilm Instax SQ6 Makes Analog Square Again appeared first on .
The  New  Fujifilm  Instax  SQ6  Makes  Analog  Square  Again 
7 weeks ago by vrzone
New Logitech G304 Wireless Gaming Mouse Makes Pro Tech Affordable
Logitech G has announced the Logitech G304 Lightspeed Wireless Gaming Mouse, a next-generation gaming mouse will bring Lightspeed wireless technology and the HERO (High-Efficiency Rated Optical) sensor to gamers everywhere in the classic Logitech style. The Logitech G304 utilizes Logitech G’s exclusive Lightspeed wireless technology to provide gamers with a superior gaming experience through speeds...

The post New Logitech G304 Wireless Gaming Mouse Makes Pro Tech Affordable appeared first on .
New  Logitech  G304  Wireless  Gaming  Mouse  Makes  Pro  Tech  Affordable 
7 weeks ago by vrzone
[App of the Week] Eat like a pro chef at home or anywhere in the world.
df94df50-902e-4baa-a90c-9b586c207e11.png
ChefsFeed
If you’re a foodie and want to know where the best places for food and drink are, you need Chef’s Feed. ​
https://itunes.apple.com/us/app/chefsfeed/id466211510?mt=8
**  Chef's  Feed  shows  which  nearby  restaurants  chefs  love  and  the  dishes  they  recommend.  app  makes  content  and  reviews  easy  to  digest  and  lets  you  make  easy  reservations  via  Opentable. 
8 weeks ago by matzner
shellharden/how_to_do_things_safely_in_bash.md at master · anordal/shellharden
Safe ways to do things in bash
Why bash?
Bash has arrays and a safe mode, which may make it just about acceptable under safe coding practices, when used correctly.
Fish is easier to use correctly, but lacks a safe mode. Prototyping in fish is therefore a good idea, provided that you know how to translate correctly from fish to bash.
Preface
This guide accompanies ShellHarden, but I also recommend ShellCheck: ShellHarden's rules shall not disagree with ShellCheck.
Bash is not a language where the correct way to do something is also the easiest. If there is anything like a driver's license for writing bash, it must be rule zero of BashPitfalls: Always use quotes.
The first thing to know about bash coding
Quote like a maniac! An unquoted variable is to be treated as an armed bomb: It explodes upon contact with whitespace. Yes, "explode" as in splitting a string into an array. Specifically, variable expansions, like $var, and also command substitutions, like $(cmd), undergo word splitting, whereby the contained string expands to an array by splitting it on any of the characters in the special $IFS variable, which is whitespace by default. This is mostly invisible, because most of the time, the result is a 1-element array, which is indistinguishable from the string you expected.
Not only that, but wildcard characters (*?) are also expanded. This process happens after word splitting, so that when a resulting word contains any wildcard characters, that word is now a wildcard pattern, expanding to any matching file paths you may happen to have. So this feature actually looks at your filesystem!
Quoting inhibits both word splitting and wildcard expansion, for variables and command substitutions.
Variable expansion:
Good: "$my_var"
Bad: $my_var
Command substitution:
Good: "$(cmd)"
Bad: $(cmd)
There are exceptions where quoting is not necessary, but because it never hurts to quote, and the general rule is to be scared when you see an unquoted variable, pursuing the non-obvious exceptions is, for the sake of your readers, questionable. It looks wrong, and the wrong practice is common enough to raise suspicion: Enough scripts are being written with broken handling of filenames that whitespace in filenames is often avoided…
The only exceptions honored by Shellharden are variables of numeric content, such as $?, $# and ${#array[@]}.
Should I use backticks?
Command substitutions also come in this form:
Correct: "`cmd`"
Bad: `cmd`
While it is possible to use this style correctly, it looks even more awkward in quotes and is less readable when nested. The consensus around this one is pretty clear: Avoid.
Shellharden rewrites these into the dollar-parenthesis form.
Should I use curly braces?
Bad: some_command $arg1 $arg2 $arg3
Extra bad (cargo culting unnecessary braces): some_command ${arg1} ${arg2} ${arg3}
Correct: some_command "${arg1}" "${arg2}" "${arg3}"
Better: some_command "$arg1" "$arg2" "$arg3"
In the "extra bad" and "correct" examples, braces compete with quotes under the limits of tolerable verbosity.
Shellharden will rewrite all these variants into the "better" form.
Braces on variable expansions are sometimes necessary (to limit the boundary of the variable name) if you absolutely want to include more string content within the same pair of quotes. This is always avoidable:
Good: "${var1}more string content$var2"
Good: "$var1""more string content""$var2"
Shellharden is neutral among these interpolation styles, but will pick the first one if asked to put down quotes anywhere.
Gotcha: Numbered arguments
Unlike normal identifier variable names (in regex: [_a-zA-Z][_a-zA-Z0-9]*), numbered arguments require braces, this time to extend the boundary of the variable name. ShellCheck says:
echo "$10"
^-- SC1037: Braces are required for positionals over 9, e.g. ${10}.
Shellharden will refuse to fix this (deemed too subtle).
Since braces are required above 9, Shellharden permits them on all numbered arguments.
Use arrays FTW
In order to be able to quote all variables, you must use real arrays when that's what you need, not whitespace separated pseudo-array strings.
The syntax is verbose, but get over it. This bashism is reason alone to drop posix compatibility for most shellscripts.
Good:
array=(
a
b
)
array+=(c)
if [ ${#array[@]} -gt 0 ]; then
rm -- "${array[@]}"
fi
Bad:
pseudoarray=" \
a \
b \
"
pseudoarray="$pseudoarray c"
if ! [ "$pseudoarray" = '' ]; then
rm -- $pseudoarray
fi
Those exceptional cases where you actually intend to split the string
Example with \v as delimiter (note the second occurence):
IFS=$'\v' read -d '' -ra a < <(printf '%s\v' "$s")
This avoids wildcard expansion, and it works no matter if the delimiter is \n. The second occurence of the delimiter preserves the last element if it's empty. For some reason, the -d option must come first, so putting the options together as -rad '', which is tempting, doesn't work. Tested with bash 4.2, 4.3 and 4.4.
Alternatively, for bash 4.4:
readarray -td $'\v' a < <(printf '%s\v' "$s")
How to begin a bash script
Something like this:
#!/usr/bin/env bash
if test "$BASH" = "" || "$BASH" -uc 'a=();true "${a[@]}"' 2>/dev/null; then
# Bash 4.4, Zsh
set -euo pipefail
else
# Bash 4.3 and older chokes on empty arrays with set -u.
set -eo pipefail
fi
shopt -s nullglob globstar
This includes:
The hashbang:
Portability consideration: The absolute path to env is likely more portable than the absolute path to bash. Case in point: NixOS. POSIX mandates /bin/sh and the existence of env, but bash is not a posix thing. If you want to be 100% covered by posix, give up – wrap it in a posix script instead.
Safety consideration: No language flavor options like -euo pipefail here! It is not actually possible when using the env redirection, but even if your hashbang begins with #!/bin/bash, it is not the right place for options that influence the meaning of the script, because it can be overridden, which would make it possible to run your script the wrong way. However, options that don't influence the meaning of the script, such as set -x would be a bonus to make overridable (if used).
What we need from Bash's unofficial strict mode, with set -u behind a feature check. We don't need all of Bash's strict mode because being shellcheck/shellharden compliant means quoting everything, which is a level beyond strict mode. Furthermore, set -u must not be used in Bash 4.3 and earlier. Because that option, in those versions, treats empty arrays as unset, which makes arrays unusable for the purposes described herein. With arrays being the second most imporant advice in this guide (after quoting), and the sole reason we're sacrificing POSIX compatibility, that's of course unacceptable: If using set -u at all, use Bash 4.4 or another sane shell like Zsh. This is easier said than done if there is a possibility that someone might run your script with an obsolete version of Bash. Fortunately, what works with set -u will also work without (unlike set -e). Thus why putting it behind a feature check is sane at all. Beware of the presupposition that testing and development happens with a Bash 4.4 compatible shell (so the set -u aspect of the script gets tested). If this concerns you, your other options are to give up compatibility (by failing if the feature check fails) or to give up set -u.
shopt -s nullglob is what makes for f in *.txt work correctly when *.txt matches zero files. The default behavior (aka. passglob) – pass the pattern as-is if it happens to match nothing – is dangerous for several reasons. As for globstar, that enables recursive globbing. Globbing is easier to use correctly than find. So use it.
But not:
IFS=''
set -f
shopt -s failglob
Setting the internal field separator to the empty string disables word splitting. Sounds like the holy grail. Sadly, this is no complete replacement for quoting variables and command substitutions, and given that you are going to use quotes, this gives you nothing. The reason you must still use quotes is that otherwise, empty strings become empty arrays (as in test $x = ""), and indirect wildcard expansion is still active. Furthermore, messing with this variable also messes with commands like read that use it, breaking constructs like cat /etc/fstab | while read -r dev mnt fs opt dump pass; do echo "$fs"; done'.
Disabling wildcard expansion: Not just the notorious indirect one, but also the unproblematic direct one, that I'm saying you should want to use. So this is a hard sell. And this too should be completely unnecessary for a script that is shellcheck/shellharden conformant.
As an alternative to nullglob, failglob fails if there are zero matches. While this makes sense for most commands, for example rm -- *.txt (because most commands that take file arguments don't expect to be called with zero of them anyway), obviously, failglob can only be used when you are able to assume that zero matches won't happen. That just means you mostly won't be putting wildcards in command arguments unless you can assume the same. But what can always be done, is to use nullglob and let the pattern expand to zero arguments in a construct that can take zero arguments, such as a for loop or array assignment (txt_files=(*.txt)).
How to use errexit
Aka set -e.
Program-level deferred cleanup
In case errexit does its thing, use this to set up any necessary cleanup to happen at exit.
tmpfile="$(mktemp -t myprogram-XXXXXX)"
cleanup() {
rm -f "$tmpfile"
}
trap cleanup EXIT
Gotcha: Errexit is ignored in command arguments
Here is a nice underhanded fork bomb that I learnt the hard way – my build script worked fine on various developer machines, but brought my company's buildserver to its knees:
set -e # Fail if nproc is not installed
make -j"$(nproc)"
Correct (command substitution in assignment):
set -e # Fail if nproc is not installed
jobs="$(nproc)"
make -j "$jobs"
Caution: Builtins like local and export are also commands, so this is still wrong:
set -e # Fail if nproc is not installed
local jobs="$(nproc)"
make -j"$jobs"
… [more]
This  makes  bash  with  errexit  practically  incomposable    it  is  possible  to  wrap  your  errexit  functions  so  that  they  still  work_  but  the  effort  it  saves  (over  explicit  error  handling)  becomes  questionable.  Consider  splitting  into  completely  standalone  scripts  instead.  from iphone
9 weeks ago by _rational

« earlier    

related tags

$1  #semrushchat  &  'bohemian  (2017)  (an  (over  (video)  **  -  000  10  12  2017-02-18  2017-04-17  2017-04-18  2017-04-19  2017-04-20  2017-04-21  2017  29th  3  3d  48:  5t  8  @diraq:  a...  a  a7  absolute  academics  acted  actresses  adaptive  add  affordable  after  again  ai  algorave:  all  almost  already  alternative)  alternator  amazon  an  analog  analytics  and  animoji  antutu  anushka  apis  app  appearance  apple's  apple  apple’s  applications  apps...  apps  april  ar  are...  are  as  auta  automotive  available  awards  bash  be  beach  beard  beautiful  bebox  becomes  best  bestsextips  bestsexvideoguide  better  bid  billion  black  box  brands  brands’  breastfeeding  breeze  brick  bring  britney  broadcom  brothers  browser  browsing  brunch  bulky  businesses  but  buy  buying  camera  can  canon’s  carbon  carpet  cars  cassandra.  cause  celebrates  cell...  certain  chaos  charger  chat  cheezburger  chef's  chefs  china’s  chromebooks...  chromebooks  circus  cities?  city  classical  code  coding  cognition  company  comparing  compass  completely  complex  composer  conditions  condos  confusing  consider  content  conversation  core  couldn't  couple  crazy  createml  crime  croons  culture  cure  dance  database  day  db.  deaf  deal  dean  debut  deepika  demos  devices  different  digest  digg  digital  disappear  dishes  dixit  dlc  doesn't  doesn’t  download  drop  early  earth  easier.  easier  easy  ee  effort  effortless  electricity  electronic  emails  emotional  employees  entertainment  entities  entity  eos  episode  errexit  error  even...  even  ever  expensive  experts  explains  explicit  explosive  explosivegspotorgasmtips  facebook  fact_  feed  female  femaleejaculatingorgasm  feuding...  feuding  figure  final  finding  fools'  for  form  foxconn  francis  friends  from...  from  fujifilm  functions  fund  g-spot  g304  galaxy  gaming  gassee  gassée  geekbench  gentle  gfxbench  givehergushingorgasm  glitch  glowing  gm  go  good  google  graphql  great  gritty  grokstyle’s  group  gspotvideo  gspotvideohelp  guardian  guy  handling)  hard  harford  has...  hashtags  have  hcci  he  head  headway  her  high  highlighted  his  history  home?  homes  hong  how?  how  htc  https://t.co/tgwugtoqsv  ideal  identified  ifttt  ikea’s  improve  in...  in  incomposable  incomprehensible  india  influential  insomnia.  installation?  instax  instead.  insurance  intelligence  internet  into...  into  investigate  ios  ipad  iphone's  iphone  iphone’s  ipo  is  islands  it's  it...  it  its  j3  jbl’s  jean  jeep  jet  jm  jodi  john's  john  join...  join  josh  journal  kajol  karaoke  keyboard  khan  kind  kong  l  lamp  latest  launch  lava  leaked  learning  lecturer  lenovo  lets  lighter  like  literally  live?  live  logitech  look  lookup  louis  love  low  luxury  m100  m3  madhuri  magnificent  mailbrush  make  makers  maleficent  manage  management  manager  manufacturers  march  market's  marketing  martin  massive  mastery  max-q  may  me  mean  miami  miamibeach  microsoft's  mid-range  mixmag  model  models  moderate  more.  more  most  moto  mouse  movement  moz  mozzers  murray  music  my  nearby  negative  new  next-level  nexus  nipples  no  nosql.  notch...  notch  notebooks  now  nursing  nvidia  object  of...  of  offer  office  official  on  oneplus  only  opentable.  or  orgasm  os  other  out  padukone  pain?  panel  part  past  pc  perfect  person  phones  photo...  photography  pillow  pinterest  pixel  place  plant  play  plex  plus  podcast  point  pointless  porn  possible  powell  practically  presebtation  price  pro  profusion  programming  pro’s  public  qualcomm  questionable.  rain  rav4  real  realestate  reality  reasons  recalls  recap  recommend.  report  reports  research  researchpsychologists  reservations  rest  restaurants  reviews  rhapsody'  right  rival  rocket  roll  ron  rt  rumor  s8  samochody  samsung  saves  scene  science  screen  scripts  search  see  semrushchat  sense?  sense...  sense  seo  set  shahrukh  share  sharma  shiny  shoppers  shows  simple  singapore  site  sites  ski  slave  slopes  smartphone  smartphones  snap  snapchat  snippets  so  solar  something  spacex  speaker  speaksee  spears  specs  spirit  spitznagel  splash  splitting  sq6  sql  square  squirt  squirting  squirting101  squirtingvideo  srk  stair  standalone  star  start  steal  still  stocking...  strategy?  stream  streaming  stronger  suited  sunset  swan  swan’  tab3  tablet  tag  takeover...  takeover  taleb  tasks  team  teams  tech  techcrunch  technologies  teclast  that  the  their  there  they  thing  this  this:  those  thriller  tick?  tim  to...  to  ton  top  total  totoro  touch  toyota  tracking  trolls  tunes  twitter  understand  underwhelming  unexpected  universa  up  update  upgrading  use  used  using  vegas  via  video  viral?  visual  vital  vivaldi  vix  volume  vs  wallpaper  wanted  water  waterfront  weigh  what  whatis  where  whereas  which  who  why  wildbit_link  will  wireless  wiring  with  women  work_  worst  worth...  worth  wp  wrap  writer  wynajem  x's  x  x5  xiaomi  x’s  years  yield  you  your  youtube  z  |      ‘appalling’  ‘bachelorette’  ‘black  ‘sailfish’  ‘timestamps’  “event”  “messages” 

Copy this bookmark:



description:


tags: