<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Salih İmran Büker on Medium]]></title>
        <description><![CDATA[Stories by Salih İmran Büker on Medium]]></description>
        <link>https://medium.com/@salogoodman?source=rss-d7d3c7801582------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F5-108jcsc1v6Ff6mPV_BA.jpeg</url>
            <title>Stories by Salih İmran Büker on Medium</title>
            <link>https://medium.com/@salogoodman?source=rss-d7d3c7801582------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 09:44:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@salogoodman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kodun Ötesinde: Yapay Zekâ Çağında Geliştirici Olmak]]></title>
            <link>https://blog.simprasuite.com/kodun-%C3%B6tesinde-yapay-zek%C3%A2-%C3%A7a%C4%9F%C4%B1nda-geli%C5%9Ftirici-olmak-47a65233c4c3?source=rss-d7d3c7801582------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a65233c4c3</guid>
            <category><![CDATA[yapay-zeka]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Salih İmran Büker]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 14:50:41 GMT</pubDate>
            <atom:updated>2025-10-01T11:23:39.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPQEJVZSkylWwMtGqrjYOw.png" /></figure><p>Yapay zekâ, özellikle 2022 yılında OpenAI tarafından yayımlanan ChatGPT ile birlikte hayatımıza hızlı ve güçlü bir giriş yapmıştır. Ardından gelen geliştirmelerle birlikte yapay zekâ yalnızca gündelik yaşamda değil, profesyonel iş süreçlerinde de vazgeçilmez bir araç haline gelmiştir. Bu noktada akıllara ‘Yapay zeka işimizi elimizden alacak mı?’ gibi sorular gelse de; ki bu sorunun cevabını yakın zamanda cevaplayabileceğimizi düşünmüyorum, aslında günümüzde üzerinde durulması gereken asıl soru şudur: Yapay zekânın yazılım geliştirme süreçlerine katkıları nelerdir ve biz bu dönüşümün neresinde konumlanabiliriz?</p><p>İtiraf etmek gerekirse, ben de bu metni yazarken yapay zekâyı aktif olarak kullanıyorum; bu kaçınılmaz değil, adeta bir zorunluluk haline gelmiştir. Yapay zekânın doğru ve etkili kullanımı kritik zaman tasarrufu sağlamakta, profesyonelliği pekiştirmekte ve genel verimliliği katbekat artırmaktadır.</p><p>Bunu biraz somut rakamlarla düşünürsek; örneğin McKinsey’nin araştırmaları, yazılım geliştiricilerin özellikle kod yazma ve belgeleme gibi görevlerde yapay zekâ destekli geliştirmenin yapay zeka destekli araçlarla <strong>iki kat daha hızlı tamamlayabildiklerini</strong> gösteriyor<a href="https://www.mckinsey.com/capabilities/mckinsey-digital/our-insights/unleashing-developer-productivity-with-generative-ai?utm_source=chatgpt.com">¹</a>.</p><p>GitHub Copilot özelinde yapılan kontrollü deneyler ise bu hızı daha da netleştiriyor: Copilot kullanan geliştiriciler görevleri <strong>yaklaşık %55 daha hızlı</strong> tamamlıyor; mesela bir iş için ortalama 1 saat 11 dakika harcarken, Copilot kullanmayanlar 2 saat 41 dakikada bitiriyor<a href="https://github.blog/news-insights/research/research-quantifying-github-copilots-impact-on-developer-productivity-and-happiness/?utm_source=chatgpt.com">²</a>.</p><p>Buraya kadar yapay zekânın yazılım geliştirmeye girişini ve sağladığı verimlilik artışlarını gördük. Ancak asıl önemli nokta bundan sonra başlıyor: <strong>Bu teknolojiyi hangi alanlarda, nasıl kullanabileceğimiz</strong>.</p><p>Yazılım geliştirme süreçlerini düşündüğümüzde yapay zekâ, yalnızca kod yazarken değil; test otomasyonundan hata ayıklamaya, dokümantasyondan proje yönetimine kadar pek çok adımda rol üstlenebiliyor. Örneğin, bir geliştirici artık hataları manuel ayıklamak yerine yapay zekâ destekli hata analizinden faydalanabiliyor. Benzer şekilde, kod gözden geçirme süreçleri (code review) artık sadece ekip arkadaşlarının değil, aynı zamanda yapay zekâ araçlarının desteğiyle de yürütülebiliyor.</p><p>Makalenin devamında bu kullanım alanlarını ayrıntılı bir şekilde ele alacağız: kod tamamlama, test süreçleri, araştırma ve öğrenme. Bununla birlikte, bu avantajların yanı sıra karşımıza çıkabilecek zorluklara da değineceğiz; veri güvenliği, bağımlılık riski ve maliyet gibi unsurlar bu başlıkların arasında yer alacak. Tüm bu konuları ise, yaklaşık üç yıllık yapay zekâ deneyimimden ve bu teknolojiyi bir kullanıcı olarak sınırlarını zorlayarak edinmiş olduğum tecrübelerimden yola çıkarak sizlerle paylaşmaktan memnuniyet duyacağım.</p><h3>Yazılım Geliştirme Süreçlerinde Yapay Zekanın Kullanımı</h3><p>Bu bölümde, yapay zekâyı yazılım geliştirme sürecinde hangi aşamalarda kullanabileceğimizi, ne kadar verim sağlayabileceğimizi ve dikkat edilmesi gereken noktaları ele alacağım. Şöyle hayal edin: Yeni bir projeye başlıyorsunuz ya da mevcut bir projede yeni bir özellik geliştirmek üzeresiniz. Elinizde bir dökümantasyon var ve bu dokümantasyona uygun şekilde kod yazmanız gerekiyor.</p><p>Benim önerim, sürece önce <strong>kendi algoritmanızı kurgulayarak</strong> başlamanız. Yani problemi parçalara ayırın, çözüm adımlarınızı kağıt üzerinde veya zihninizde netleştirin. Ardından yapay zekâ ile bu algoritmayı tartışın; refaktör edilebilecek alanları, olası mantık hatalarını ve optimizasyon fırsatlarını birlikte değerlendirin.</p><p>Sonraki adımda algoritmanızı bizzat kodlayarak bir <strong>temel şablon</strong> oluşturun. Bu noktada yapay zekâ destekli geliştirme araçlarını (örneğin ChatGPT’nin VS Code eklentisi veya GitHub Copilot) kullanarak, yazdığınız kodu projenin genel standartlarına ve mevcut mimariye uygunluk açısından kontrol ettirin.</p><p>İlk kontrolden sonra, benim de kişisel olarak tercih ettiğim gibi, yapay zekânın modunu daha derinlemesine analiz yapabilen bir moda (örneğin Codex’te “agent” modu) alabilir ve tespit edilen sorunlara göre kodunuzu refaktör etmesini isteyebilirsiniz. Refaktör işlemi tamamlandıktan sonra mutlaka değişiklikleri gözden geçirin, mantığınıza uymayan veya proje standartlarına aykırı gördüğünüz kısımları manuel olarak düzeltin.</p><p>Bu iterasyonları birkaç kez tekrarladığınızda, sadece daha temiz ve sürdürülebilir bir kod elde etmekle kalmaz, aynı zamanda yapay zekânın getirdiği önerilerden de <strong>kendi öğreniminize katkı sağlayacak</strong> çıkarımlar elde edersiniz. Böylece hem projeniz hem de kişisel gelişiminiz açısından kazançlı bir süreç ortaya çıkar.</p><h3>Test Süreçlerinde Yapay Zekanın Kullanımı</h3><p>Şimdi sırada yeni bir feature geliştirdiniz, kodlar bitti, sıra testlere geldi. Normalde tek tek unit test yazmanız, entegrasyon senaryolarını belirlemeniz, hatta UI tarafında manuel tıklamalar yapmanız gerekir. Bu hem zaman alır hem de insan hatasına açık bir süreçtir.</p><p>Benim önerim, burada da sürece yapay zekâyı dahil etmeniz. Önce yazdığınız fonksiyonun amacını yapay zekâya anlatın ve ondan bu fonksiyon için uygun test senaryoları üretmesini isteyin. Genelde AI, sizin gözden kaçırdığınız edge case’leri bile önerebiliyor. Böylece test kapsamınız çok daha geniş oluyor.</p><p>Bundan sonra n8n<a href="https://n8n.io/">³</a> gibi araçlarla süreci tamamen otomatikleştirebilirsiniz. Örneğin, projenizde CI pipeline’a bir n8n akışı bağlayarak deployment tetiklendiğinde yapay zekâya testleri çalıştırmasını ve sonuçları Slack’e raporlamasını sağlayabilirsiniz. Böylece her push’tan sonra hatalar otomatik olarak detaylı bir şekilde raporlanabilir.</p><p>UI tarafında da yapay zekâdan destek almak mümkün. Mabl<a href="https://www.mabl.com/">⁴</a> gibi araçlar, kullanıcının gerçekten tıklayacağı adımları taklit ederek sizin için E2E testler hazırlıyor. Sonra tek bir komutla tüm bu senaryoları çalıştırıp ekranınızda raporu görüyorsunuz.</p><p>Tabii ki bu sürecin sonunda oturup sonuçları kontrol etmek önemli. Yapay zekânın önerdiği testler bazen fazla kapsamlı ya da proje standartlarına uymayan şekilde olabilir. Ben her test yazımından sonra değişiklikleri not ederim, gerekli gördüklerimi manuel olarak revize ederim. Bu yol hem kodun güvenilirliğini artırıyor hem de sürekli yeni şeyler öğrenmemi sağlıyor.</p><h3>Araştırma ve Öğrenme Süreçlerinde Yapay Zeka Kullanımı</h3><p>Şimdi bir de şöyle bir sahne düşünün: Yeni bir teknoloji öğrenmeniz gerekiyor, mesela bir GraphQL API entegre edeceksiniz. Normalde oturur Google’da döküman ararsınız, blog yazılarını okur, YouTube videolarına göz atarsınız. Bu süreç bazen saatler, hatta günler sürebilir.</p><p>İşte burada yapay zekâ devreye giriyor. Ben genelde önce temel ihtiyacımı anlatan kısa bir prompt yazarım:</p><blockquote><em>“Ruby on Rails projesine GraphQL nasıl entegre edilir, bana adım adım anlat.”</em></blockquote><p>ChatGPT veya benzeri modeller, önce bir genel bakış sunar, ardından siz detaya indikçe örnek kodlar üretir, hatta ilgili döküman linklerini paylaşır. Bu şekilde bilgiye ulaşmak çok daha hızlı olur.</p><p>Öğrenme sürecini daha da etkili hale getirmek için yapay zekâyı bir “tartışma ortağı” gibi kullanabilirsiniz. Örneğin, kafanıza takılan bir konuyu sadece sormakla kalmayıp, “Bu yaklaşımın avantajı ve dezavantajı nedir? Alternatifleri nelerdir?” diye sorgulayabilirsiniz. Ben bu şekilde hem bilgiyi daha derinlemesine öğreniyor hem de konunun farklı bakış açılarını keşfetmiş oluyorum.</p><p>Bir diğer güçlü kullanım yöntemi ise yapay zekâya aktif olarak soru sormak yerine ondan sizi sınamasını istemek. Örneğin, yeni öğrendiğiniz bir konuyu anlatmasını isteyebilir, ardından “Bana bu konuyla ilgili 5 soruluk bir mini test hazırla” diyebilirsiniz. Böylece sadece okumakla kalmaz, kendinizi test ederek ne kadar öğrendiğinizi ölçersiniz.</p><p>Son olarak, yapay zekâ ile birlikte çalışırken kendi notlarınızı tutmak ve öğrenilenleri düzenli olarak tekrar etmek öğrenme sürecini kalıcı hale getirir. Ben genelde yapay zekâdan aldığım cevapları bir not uygulamasına kaydediyor ve daha sonra kısa bir özet çıkarıyorum. Bu yöntem, konuyu sadece yüzeysel öğrenmek yerine gerçekten içselleştirmemi sağlıyor.</p><h3>Dikkat Edilmesi Gereken Noktalar</h3><p>Buraya kadar yapay zekânın ne kadar faydalı olduğundan bahsettik ama bir de işin dikkat edilmesi gereken tarafı var. Yeni yazdığınız bir fonksiyonu ChatGPT’ye gönderiyorsunuz, o da size harika görünen bir çözüm öneriyor. Burada yapmanız gereken ilk şey, “Bu çözüm mantıklı mı?” diye kendinize sormak. Yapay zekâ çok ikna edici yanıtlar verebilir ama bazen mantıksal hatalar yapabilir, halüsinasyona uğrayabilir veya projenizin ihtiyaçlarına tam olarak uymayan sonuçlar çıkarabilir.</p><p>Bir başka önemli konu veri gizliliği. Gizlilik şartları olan bir proje üzerinde çalışıyorsanız, kodu veya hassas verileri doğrudan yapay zekâya göndermek doğru olmayabilir. Ben bu tür durumlarda verileri anonimleştirip sadece algoritmayı paylaşıyor, böylece güvenlik riskini en aza indiriyorum.</p><p>Ve tabii bir de bağımlılık konusu var. Yapay zekâya her şeyi sormaya alışmak gerçekten çok kolay, ancak uzun vadede bu durum kendi problem çözme kaslarımızı köreltebilir. Bana göre en dikkat edilmesi gereken nokta da tam olarak burası. Ben de bir dönem yapay zekâya fazlasıyla bağımlı hale geldiğimi fark ettim. O noktada neredeyse kendi düşünme sürecimi devre dışı bırakmış, her şeyi yapay zekâya yaptırır hale gelmiştim. Bunun farkına vardığımda sürecin ciddiyetini anladım ve acilen bu alışkanlığı değiştirdim.</p><p>Kendi yaklaşımımı şu şekilde yeniden kurguladım: Önce problemi kendim çözmeye çalışıyor, ardından ortaya çıkan çözümü yapay zekâya gönderip eksiklerimi veya alternatifleri görerek ilerliyorum. Bu yöntem hem bağımsız düşünme yeteneğimi korumamı sağladı hem de her iterasyonda yeni şeyler öğrenmem için bir fırsat sundu.</p><p>Son olarak, kullandığınız aracın maliyetini göz önünde bulundurun. Özellikle API tabanlı çözümler yoğun kullanımda ciddi faturalara dönüşebilir. Bu yüzden yapay zekâdan her adımda destek almak yerine kritik anlarda kullanmayı tercih etmek, hem bütçeyi korur hem de aracı daha bilinçli kullanmanızı sağlar.</p><h3>Sonuç</h3><p>Yapay zekâ, yazılım geliştirme dünyasında artık geçici bir trend değil; geleceği şekillendiren bir paradigma değişimidir. Kod yazma biçimimizi, test süreçlerimizi ve ekip içi iş birliğimizi kökten dönüştürerek geliştiricinin rolünü yeniden tanımlıyor. Artık sadece kod yazan değil, problemi tanımlayan, yapay zekâyı yönlendiren ve çıkan sonuçları stratejik olarak değerlendiren bir geliştirici profili ortaya çıkıyor.</p><p>Bu dönüşüm, geliştiriciler için büyük bir fırsat: Daha yaratıcı, daha stratejik ve daha üretken bir yazılım geliştirme deneyimi. Ancak aynı zamanda sorumluluk da gerektiriyor. Veri gizliliği, algoritmik şeffaflık ve insan-yapay zekâ iş birliğinin dengesi; bu yeni dönemin en kritik başlıkları olmaya devam edecek.</p><p>Benim vizyonum, yapay zekânın geliştiriciyi asla tamamen devre dışı bırakmayacağı, tam tersine onu daha donanımlı ve etkili bir problem çözücüye dönüştüreceği yönünde. Bugün bilinçli ve dengeli kullanım alışkanlıkları kazanırsak, gelecekte yazılım geliştirme süreçlerinde yalnızca daha hızlı değil, aynı zamanda daha doğru, daha etik ve daha sürdürülebilir sonuçlar üreteceğiz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a65233c4c3" width="1" height="1" alt=""><hr><p><a href="https://blog.simprasuite.com/kodun-%C3%B6tesinde-yapay-zek%C3%A2-%C3%A7a%C4%9F%C4%B1nda-geli%C5%9Ftirici-olmak-47a65233c4c3">Kodun Ötesinde: Yapay Zekâ Çağında Geliştirici Olmak</a> was originally published in <a href="https://blog.simprasuite.com/">Simpra Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rest vs GraphQL in Rails]]></title>
            <link>https://medium.com/@salogoodman/rest-vs-graphql-in-rails-ce44c53a2dcc?source=rss-d7d3c7801582------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce44c53a2dcc</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <dc:creator><![CDATA[Salih İmran Büker]]></dc:creator>
            <pubDate>Tue, 16 Jul 2024 11:54:34 GMT</pubDate>
            <atom:updated>2024-07-16T11:55:53.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptnWSJ9f1SoHIIDL5I24yA.png" /></figure><h3><strong>Introduction</strong></h3><p>Welcome to my first blog post. In this post, I will talk about the main differences between GraphQL and REST API, but there will be no winner at the end of the post, I will just talk about the main differences and the use cases of these API types. Have a good read.</p><h4>What is API</h4><p>Before we can discuss an issue, we need to know what it is. Here is a brief background about APIs. APIs (Application Programming Interface) are interfaces that enable communication between software. It makes it possible for applications to exchange data and share various functions.</p><p>There are different types of APIs actively used in the software world. For example REST, SOAP, GraphQL, WebSocket, gRPC, etc. We can extend the list, but in this post we will focus on two API types. REST and GraphQL.</p><p>We will also use the Ruby on Rails framework, which I also like to use while making this comparison. In this way, you will also see how you can develop a simple API with Ruby on Rails. Let’s get started.</p><h4>What is REST</h4><p>Now let’s talk a little bit about Rest. Rest APIs are an architectural style used to develop web services that run over the HTTP protocol. REST API allows clients to access and interact with specific resources.</p><p>Everything is represented as a resource and these resources are accessed through specific URLs. JSON is usually used as the data format, but XML can also be used. Rest api has four basic HTTP methods that it uses. These methods are:<br>1. GET: Used to read resources.<br>2. POST: Used to create a new resource.<br>3. PUT: Used to update an existing resource.<br>4. DELETE: Used to delete resources.</p><p>Of course, you don’t have to depend on these methods. So you can update or delete a resource with a get method. But this is not a recommended use.</p><p>In short, REST API is an API architecture where we can make a request for a resource and get the results we want in response.</p><h4>What is GraphQL</h4><p>I realize that you are drowning in theoretical knowledge, but I will finally talk about what GraphQL is and move on to the implementation. So GraphQL is a flexible query language developed and supported by Facebook. It’s good that a big company stands behind it, right?</p><p>By flexibility, I mean that clients can query the data they need through specific fields. This prevents excessive or incomplete data transfer.</p><p>Everything in GraphQL is based on a powerful type system. Types define the data structure and determine what data clients can retrieve. Usually all queries and mutations are performed from a single endpoint, which simplifies API management.</p><p>So what is this query and mutations? Queries are used to retrieve data. Clients can query specific fields they want from the server. Just like the GET method in REST, right? Mutations are used to create, update or delete data. Similar to POST, PUT, DELETE operations in REST.</p><p>Finally, we need to talk about Subscription. Because this feature solves a big problem in rest. Providing real-time data flow. While in Rest we need additional technologies such as WebSocket to provide real-time data flow, in GraphQL we can provide real-time data flow thanks to Subscription.</p><p>Now let’s put all this into practice. Let’s get started.</p><h4>General Structure of the Application</h4><p>Now we will develop a simple library API. We will use both REST API and GraphQL in the same application and we will see the differences together.</p><p>Here are the models we will use in this application. The book model will have the year of publication and will have an author. Authors can have more than one book. Also, each of the books will be located on a shelf. The library will have users and each user can rent up to three books. We will also develop a real-time commenting structure for users to talk about books.</p><p>This is the general structure of the application. Now let’s start with application installations.</p><h4>Creating a Rails Application</h4><p>First things first we need to create a Rails application. For this I type this command in my console:</p><pre>rails new library_app --database=postgresql</pre><p>In this way, we created a rails application whose database is Postgresql. You can use other databases if you want, it’s up to you.</p><p>Now let’s create our models respectively:</p><pre>rails generate model Author name:string</pre><pre>rails generate model Shelf name:string</pre><pre>rails generate model User name:string user:references</pre><pre>rails generate model Book name:string publication_year:integer category:string author:references shelf:references</pre><p>In this way, we created our models.</p><p>To develop GraphQL with Rails, we install these two useful gems. Let’s add it to the Gemfile:</p><pre>gem &#39;graphql&#39;<br>gem &#39;graphiql-rails&#39;, group: :development</pre><p>Type Bundle install in the console to install the gems:</p><pre>bundle install</pre><p>To install GraphQL in our application, we enter the following commands in the console:</p><pre>rails generate graphql:install</pre><p>When we execute this command, you can see that a folder named graphql is created under the app directory.</p><p>Finally we will define the routes in config/routes.rb:</p><pre>Rails.application.routes.draw do<br>  if Rails.env.development?<br>    mount GraphiQL::Rails::Engine, at: &quot;/graphiql&quot;, graphql_path: &quot;/graphql&quot;<br>  end<br><br>  post &quot;/graphql&quot;, to: &quot;graphql#execute&quot;<br><br>  resources :books<br>  resources :authors<br>  resources :shelves<br>  resources :users<br>end</pre><p>If we are in a development environment, this code will redirect us to graphiql, the perfect gem that we have installed. Thanks to the graphiql gem we will have a GraphQL interface.</p><p>Now we are ready to define the relationships and develop our implementation.</p><h4>Defining Relationships</h4><p>Relationships for book model in “app/models/book.rb”:</p><pre>class Book &lt; ApplicationRecord<br>  belongs_to :author<br>  belongs_to :shelf<br>  belongs_to :user, optional: true<br>end</pre><p>Relationships for author model in “app/models/author.rb”:</p><pre>class Author &lt; ApplicationRecord<br>  has_many :books<br>end</pre><p>Relationships for shelf model in “app/models/shelf.rb”:</p><pre>class Shelf &lt; ApplicationRecord<br>  has_many :books<br>end</pre><p>Relationships for user model in “app/models/user.rb”:</p><pre>class User &lt; ApplicationRecord<br>  has_many :books<br>end</pre><p>Finally, we’ll create a database and do the migrations.</p><pre>rails db:create<br>rails db:migrations</pre><h4>Create Controllers, Types and Mutations</h4><p>First of all, we need to create controllers in rails to manage our models in REST api. For this, we will apply the following command for each model:</p><pre>rails generate controller ModelName</pre><p>The controllers you create will be created under the app/controllers directory and will look like this:</p><pre>class ModelNameController &lt; ApplicationController<br><br>end</pre><p>They are empty for now but we will fill them. Now we will create our types for GraphQL. For the book type, we enter the following command in the console:</p><pre>rails generate graphql:object Book name:String! publicationYear:Int! category:String! author:Author! shelf:Shelf! user:User</pre><p>After this command, a file called book_type.rb will be created under the “app/graphql/types” directory. This file is a GraphQL type file that defines a schema for GraphQL and specifies which data types can be accessed through the API. It should look like this:</p><pre>module Types<br>  class BookType &lt; Types::BaseObject<br>    field :id, ID, null: false<br>    field :name, String<br>    field :publication_year, Integer<br>    field :category, String<br>    field :created_at, GraphQL::Types::ISO8601DateTime, null: false<br>    field :updated_at, GraphQL::Types::ISO8601DateTime, null: false<br>    field :author, Types::AuthorType, null: false<br>    field :shelf, Types::ShelfType, null: false<br>    field :user, Types::UserType<br>  end<br>end</pre><p>We also create our other types:</p><pre>rails generate graphql:object Author name:String!<br>rails generate graphql:object Shelf name:String!<br>rails generate graphql:object User name:String!</pre><p>We now have a controller and type for all our models. First, let’s create fake data to get some results from our requests and queries. For this we will seed the database and use a gem called Faker. To do this, we add the relevant gem to the gemfile.</p><pre>gem &#39;faker&#39;</pre><p>Then we install gem by bundle install.</p><p>Now we write the following codes in my ‘db/seeds.rb’ file:</p><pre>40.times do<br>  author = Author.create(<br>    name: Faker::Book::author<br>  )<br>end<br><br>12.times do |i|<br>  shelf = Shelf.create(<br>    name: &quot;#{i+1}. shelf&quot;<br>  )<br>end<br><br>500.times do<br>  author = Author.offset(rand(Author.count)).first<br>  shelf = Shelf.offset(rand(Shelf.count)).first<br><br>  Book.create(<br>    name: Faker::Book.title,<br>    publication_year: rand(1900..2024),<br>    category: Faker::Book.genre,<br>    author: author,<br>    shelf: shelf<br>  )<br>end</pre><p>In this code we created 40 authors with random names, 12 shelves with an ordered number of shelves and finally 500 books with random authors and random shelves. Let’s put it into action:</p><pre>rails db:seed</pre><p>Now we have a data set. We need to query over this. Let’s start developing an API for this. First, let’s see what we want. We may simply want to see books. Let’s add something to our books controller for that:</p><pre>  def index<br>    @books = Book.all<br>    render json: @books, status: :ok<br>  end</pre><p>We will be able to use our index function thanks to the “resources :books” we defined in the routes. In our index function, we want it to print all the books to a json file for us. Let’s start our rails server and try. For this I enter the following command in the console:</p><pre>rails server</pre><p>I now have a host running locally. I use Postman to send requests to the server. But I need to check which route I should send requests to. For this I enter the following command in the console:</p><pre>rails routes</pre><p>Let’s focus on this area.</p><pre> books GET    /books(.:format)                          books#index<br>       POST   /books(.:format)                          books#create<br> new_book GET    /books/new(.:format)                   books#new<br> edit_book GET    /books/:id/edit(.:format)             books#edit<br> book GET    /books/:id(.:format)                       books#show<br> PATCH  /books/:id(.:format)                            books#update<br> PUT    /books/:id(.:format)                            books#update<br> DELETE /books/:id(.:format)                            books#destroy</pre><p>As you can see, we need to make a GET /books request for “index”. Let’s do it. In the request section of Postman, we type GET <a href="http://127.0.0.1:3000/books">http://127.0.0.1:3000/books</a> and send it.</p><pre>{<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;Nectar in a Sieve&quot;,<br>        &quot;publication_year&quot;: 2010,<br>        &quot;category&quot;: &quot;Essay&quot;,<br>        &quot;author_id&quot;: 31,<br>        &quot;created_at&quot;: &quot;2024-06-30T20:20:03.533Z&quot;,<br>        &quot;updated_at&quot;: &quot;2024-06-30T20:20:03.533Z&quot;,<br>        &quot;shelf_id&quot;: 1<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;name&quot;: &quot;Have His Carcase&quot;,<br>        &quot;publication_year&quot;: 1946,<br>        &quot;category&quot;: &quot;Suspense/Thriller&quot;,<br>        &quot;author_id&quot;: 105,<br>        &quot;created_at&quot;: &quot;2024-06-30T20:20:03.546Z&quot;,<br>        &quot;updated_at&quot;: &quot;2024-06-30T20:20:03.546Z&quot;,<br>        &quot;shelf_id&quot;: 34<br>    },<br>    {<br>        &quot;id&quot;: 3,<br>        &quot;name&quot;: &quot;Absalom, Absalom!&quot;,<br>        &quot;publication_year&quot;: 1929,<br>        &quot;category&quot;: &quot;Mythology&quot;,<br>        &quot;author_id&quot;: 98,<br>        &quot;created_at&quot;: &quot;2024-06-30T20:20:03.556Z&quot;,<br>        &quot;updated_at&quot;: &quot;2024-06-30T20:20:03.556Z&quot;,<br>        &quot;shelf_id&quot;: 20<br>    },<br>...</pre><p>If you examine this field, you can see that 500 books are also listed. Let’s do it from GraphQL. To do this, we need to create a query. In Rails, we create queries in the file “app/graphql/types/query_type.rb”. Below is a query where we can fetch all the books.</p><pre>module Types<br>  class QueryType &lt; Types::BaseObject<br>    field :books, [Types::BookType], null: false<br><br>    def books<br>      Book.all<br>    end<br>  end<br>end</pre><p>Let’s examine this code fragment in detail. ’field :books’ specifies the name of the field to be used in the GraphQL query. Here the name of the field is defined as books. ‘[Types::BookType]’ specifies the type of data that the ‘books’ field will return. The square brackets ‘[ ]’ indicate that this field will return a list. ‘null: false’ indicates that the books field cannot be null. This means that this query will always return a list; the list can be empty but not null.</p><p>You may have noticed that there is a method under Field. This function (def books) allows us to get all the books. However, you may be asking a question like this. How does the field know that it will execute this method? The answer is simple. The method we wrote has a special name “Resolver method”. In Ruby, GraphQL automatically finds a resolver method for the field definition. This is based on the assumption that the field name will call a method defined with the same name. So it is completely hypothetical. You can see for yourself what can happen if you don’t create a resolver method.</p><p>Now go to <a href="http://127.0.0.1:3000/graphiql">http://127.0.0.1:3000/graphiql</a> in your favorite browser and access GraphiQL. Then create a query:</p><pre>query{<br>  books{<br>    id<br>    name<br>    category<br>    author{<br>      name<br>    }<br>    shelf{<br>      id<br>    }<br>  }<br>}</pre><p>This query will retrieve all books with their ids, names, categories, authors and authors’ names, shelves and shelf names. When we run it, you will get the following output:</p><pre>&quot;data&quot;: {<br>    &quot;books&quot;: [<br>      {<br>        &quot;id&quot;: &quot;1&quot;,<br>        &quot;name&quot;: &quot;Nectar in a Sieve&quot;,<br>        &quot;category&quot;: &quot;Essay&quot;,<br>        &quot;author&quot;: {<br>          &quot;name&quot;: &quot;Shamika Schowalter&quot;<br>        },<br>        &quot;shelf&quot;: {<br>          &quot;id&quot;: &quot;1&quot;<br>        }<br>      },<br>      {<br>        &quot;id&quot;: &quot;2&quot;,<br>        &quot;name&quot;: &quot;Have His Carcase&quot;,<br>        &quot;category&quot;: &quot;Suspense/Thriller&quot;,<br>        &quot;author&quot;: {<br>          &quot;name&quot;: &quot;Serafina Blanda&quot;<br>        },<br>        &quot;shelf&quot;: {<br>          &quot;id&quot;: &quot;34&quot;<br>        }<br>      },<br>      {<br>        &quot;id&quot;: &quot;3&quot;,<br>        &quot;name&quot;: &quot;Absalom, Absalom!&quot;,<br>        &quot;category&quot;: &quot;Mythology&quot;,<br>        &quot;author&quot;: {<br>          &quot;name&quot;: &quot;Jae Bednar&quot;<br>        },<br>        &quot;shelf&quot;: {<br>          &quot;id&quot;: &quot;20&quot;<br>        }<br>      },<br>...</pre><p>What I really want you to see here is that we can bring the field we want. For example, if I want, I can remove the authors from this query and get a result without authors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZRq_Tn_yOqGvj6w4lEYRA.png" /></figure><p>It is not impossible to do this with the REST API. However, we need to create a different endpoint for each change. So it is not at the initiative of the API user. The user sees what the developer wants, he cannot customize the request. This is what is meant by flexibility.</p><p>Now let’s create a mutation and a POST request and talk about the differences between them. Now the mutations and endpoints we will create will be used to create users and assign books to them. We will also control that the user cannot get more than three books.</p><p>First, let’s start by writing our endpoints. For this, we write the following codes to the user controller:</p><pre>class UsersController &lt; ApplicationController<br>  skip_before_action :verify_authenticity_token, only: [:create]<br><br>  def create<br>    @user = User.create(user_params)<br><br>    if @user.save<br>      render json: @user, status: :created<br>    else<br>      render json: @user.errors, status: :unprocessable_entity<br>    end<br>  end<br><br>  private<br><br>  def user_params<br>    params.require(:user).permit(:name)<br>  end<br><br>end</pre><p>With this controller we will be able to create a new user. Let’s do it with Postman. First, let’s see which endpointe to request with the rails routes command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRYfI-oV7FFtPEMnSTji8g.png" /></figure><p>As you can see, POST /users will run our create method. Now send a request to <a href="http://127.0.0.1:3000/users">http://127.0.0.1:3000/users</a>. We need to write the name of our user in the body of the request:</p><pre>{<br>    &quot;user&quot;: {<br>        &quot;name&quot;: &quot;Dummy Name&quot;<br>    }<br>}</pre><p>We need to get that respons:</p><pre>{<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Dummy Name&quot;,<br>    &quot;created_at&quot;: &quot;2024-07-11T11:13:16.774Z&quot;,<br>    &quot;updated_at&quot;: &quot;2024-07-11T11:13:16.774Z&quot;<br>}</pre><p>User created. We can’t use the API to confirm this because we haven’t written an endpoint for this. We will use the console that Rails offers us by typing <em>rails consol</em> in our console. Let’s see all users with the <em>user.all</em> command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bt0noURdBdzWDsjoBZ5ELw.png" /></figure><p>Now let’s do it as a mutation. To create a mutation, we need to create a new ruby file under the “app/graphql/mutations” directory. You can give the mutation any name you want. I will create it as create_user.rb. I write the following codes into the file:</p><pre>module Mutations<br>  class CreateUser &lt; BaseMutation<br>    argument :name, String, required: true<br><br>    field :user, Types::UserType, null: false<br>    field :errors, [String], null: false<br><br>    def resolve(name:)<br>      user = User.new(name: name)<br>      if user.save<br>        {<br>          user: user,<br>          errors: [],<br>        }<br>      else<br>        {<br>          user: nil,<br>          errors: user.errors.full_messages,<br>        }<br>      end<br>    end<br>  end<br>end</pre><p>We create the CreateUser class whose module is mutation and inherits from the BaseMutation class. It will be named as Argument and will be compulsory. It will return two fields named user and errors. Resolve method is the method that runs when mutation is called.</p><p>Now this mutation we have developed must make itself known. For this, let’s introduce our mutation in the mutation_type.rb file under the “app/graphql/types” directory:</p><pre>module Types<br>  class MutationType &lt; Types::BaseObject<br>    field :create_user, mutation: Mutations::CreateUser<br>  end<br>end</pre><p>Now to use the mutation, we open Graphiql and write the following:</p><pre>mutation{<br>  createUser(input:{name: &quot;Dummy Name GraphQL&quot;}){<br>   user{<br>      id<br>      name<br>    }<br>    errors<br>  }<br>}</pre><p>If we receive the following response after sending the request, our operation is successful:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;createUser&quot;: {<br>      &quot;user&quot;: {<br>        &quot;id&quot;: &quot;2&quot;,<br>        &quot;name&quot;: &quot;Dummy Name GraphQL&quot;<br>      },<br>      &quot;errors&quot;: []<br>    }<br>  }<br>}</pre><p>Now let’s talk about the single endpoint goodness of GraphQL. Let’s write a new mutation for GraphQL and a new endpoint for REST. We can access each mutation, query and subscription we develop in GraphQL through a single endpoint. However, in REST, we need to follow a different endpoint route for each request.</p><p>In this example, we will enable users to rent books. While doing this, we will check the number of books belonging to the user and if the user has 3 books, they will not be able to rent books. First I implement a method called add_book in my user_controller.rb file:</p><pre>  def add_book<br>    @user = User.find(params[:id])<br>    @book = Book.find(params[:book_id])<br>    @book_count = @user.books.count<br><br>    if @book_count &lt; 3<br>      if @user.books &lt;&lt; @book<br>        render json: @user.books, status: :ok<br>      else<br>        render json: @user.errors, status: :unprocessable_entity<br>      end<br>    else<br>       render json: { error: &#39;This user has reached the book limit and cannot add books!&#39; }, status: :unprocessable_entity<br>    end<br>  end</pre><p>Now we will need a route to use this method. For this I write the following under <em>resources :users</em> at the bottom of my routes.rb file:</p><pre>  resources :users do<br>    member do<br>      post &#39;add_book&#39;<br>    end<br>  end</pre><p>With this action, we have created an additional route other than index, show, new, create, edit, update, and destroy. Now let’s see the route created and test it. I open my console and type rails routes:</p><pre> add_book_user POST   /users/:id/add_book(.:format)  users#add_book</pre><p>You can see the route forming. Now let’s make a request to this endpoint and assign a book to the user. The request route should be POST <a href="http://127.0.0.1:3000/users/5/add_book">http://127.0.0.1:3000/users/5/add_book</a> and the body should be as follows:</p><pre>{<br>    &quot;book_id&quot;: 10<br>}</pre><p>When the request is sent, the response will be as follows:</p><pre>    {<br>        &quot;user_id&quot;: 5,<br>        &quot;author_id&quot;: 19,<br>        &quot;shelf_id&quot;: 5,<br>        &quot;id&quot;: 10,<br>        &quot;name&quot;: &quot;This Lime Tree Bower&quot;,<br>        &quot;publication_year&quot;: 1939,<br>        &quot;category&quot;: &quot;Short story&quot;,<br>        &quot;created_at&quot;: &quot;2024-06-30T20:20:03.579Z&quot;,<br>        &quot;updated_at&quot;: &quot;2024-07-14T14:58:24.540Z&quot;<br>    }</pre><p>Now let’s try to assign a book to a user with three books and see the error:</p><pre>{&quot;error&quot;:&quot;This user has reached the book limit and cannot add books!&quot;}</pre><p>In a real application, there will be many more scenarios, so there will be many more controls and methods. But since this is an educational application, I don’t need them.</p><p>Now let’s finally do this in graphQL and let’s move to the end. I create a new file called add_book_to_user.rb in my mutation folder. Then I write my codes in it:</p><pre>module Mutations<br>  class AddBookToUser &lt; BaseMutation<br>    argument :user_id, ID, required: true<br>    argument :book_id, ID, required: true<br><br>    field :user, Types::UserType, null: true<br>    field :book, Types::BookType, null: true<br>    field :errors, [String], null: false<br><br>    def resolve(user_id:, book_id:)<br>      user = User.find_by(id: user_id)<br>      book = Book.find_by(id: book_id)<br><br>      unless user &amp;&amp; book<br>        return {<br>          user: nil,<br>          book: nil,<br>          errors: [&quot;User or book not found&quot;]<br>        }<br>      end<br><br>      book_count = user.books.count<br><br>      if book_count &lt; 3<br>        if user.books &lt;&lt; book<br>          {<br>            user: user,<br>            book: book,<br>            errors: []<br>          }<br>        else<br>          {<br>            user: nil,<br>            book: nil,<br>            errors: book.errors.full_messages<br>          }<br>        end<br>      else<br>        {<br>          user: nil,<br>          book: nil,<br>          errors: [&#39;This user has reached the book limit and cannot add books!&#39;]<br>        }<br>      end<br>    end<br>  end<br>end</pre><p>I introduce my mutation in my mutation_type.rb file:</p><pre>module Types<br>  class MutationType &lt; Types::BaseObject<br>    field :create_user, mutation: Mutations::CreateUser<br>    field :add_book_to_user, mutation: Mutations::AddBookToUser<br>  end<br>end</pre><p>Now let’s throw our request to GraphiQL and see the response:</p><pre>mutation{<br>  addBookToUser(input:{bookId: 42, userId: 6}){<br>    book{<br>      name<br>      user{<br>        name<br>      }<br>    }<br>  }<br>}</pre><p>I assign the book with ID 42 to the user with ID 6:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;addBookToUser&quot;: {<br>      &quot;book&quot;: {<br>        &quot;name&quot;: &quot;By Grand Central Station I Sat Down and Wept&quot;,<br>        &quot;user&quot;: {<br>          &quot;name&quot;: &quot;Dummy Name&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>As you can see, the book assignment to the user was successful. Now let’s try to assign a book to a user with 3 books and see the error message returned. For this we add errors field to the request:</p><pre>mutation{<br>  addBookToUser(input:{bookId: 48, userId: 6}){<br>    book{<br>      name<br>      user{<br>        name<br>      }<br>    }<br>    errors<br>  }<br>}</pre><p>Now let’s take a look at the answer:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;addBookToUser&quot;: {<br>      &quot;book&quot;: null,<br>      &quot;errors&quot;: [<br>        &quot;This user has reached the book limit and cannot add books!&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>As you can see, we got the error “This user has reached the book limit and cannot add books!” here too.</p><h4>Summary</h4><p>To summarize everything we have done, there are advantages and disadvantages of both API types. GraphQL offers more flexible and powerful data querying capabilities. It provides the advantage of pulling related data in a single query, especially when there are specific data needs on the client side. REST API has the advantages of simplicity and widespread use. It is ideal for basic CRUD operations and working with standard HTTP methods.</p><p>GraphQL is a technology widely used in mobile applications, SPAs, applications with complex data needs. REST is widely used in traditional web applications, microservice architectures, and projects with simple data access requirements.</p><p>I wanted to explain these differences to you through a sample application. I hope I was successful in this matter. Of course, there is much more to talk about. For example the comparison of Subscription structure and socket technology. Or how to solve the n+1 problem on these technologies. But these are topics for other blog posts. Stay following for that. This is the end of the blog post, thanks for reading this far. Good coding.</p><h4>References</h4><ul><li><a href="https://graphql.org/learn/">Introduction to GraphQL | GraphQL</a></li><li><a href="https://guides.rubyonrails.org/getting_started.html">Getting Started with Rails - Ruby on Rails Guides</a></li><li><a href="https://github.com/faker-ruby/faker">GitHub - faker-ruby/faker: A library for generating fake data such as names, addresses, and phone numbers.</a></li><li><a href="https://github.com/rmosolgo/graphiql-rails">GitHub - rmosolgo/graphiql-rails: Mount the GraphiQL query editor in a Rails app</a></li><li><a href="https://github.com/rmosolgo/graphql-ruby">GitHub - rmosolgo/graphql-ruby: Ruby implementation of GraphQL</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce44c53a2dcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>