<?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 Miguel Ponce G on Medium]]></title>
        <description><![CDATA[Stories by Miguel Ponce G on Medium]]></description>
        <link>https://medium.com/@miguelponceg87?source=rss-43996289094b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yzkAfcJwslsqe9KJ</url>
            <title>Stories by Miguel Ponce G on Medium</title>
            <link>https://medium.com/@miguelponceg87?source=rss-43996289094b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:59:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@miguelponceg87/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[How to implement GraphQL in ASP.Net Core Web API (.NET 6) using HotChocolate]]></title>
            <link>https://medium.com/globallogic-latam/how-to-implement-graphql-in-asp-net-core-web-api-net-6-using-hotchocolate-a30b57b8a989?source=rss-43996289094b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a30b57b8a989</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[hot-chocolate]]></category>
            <dc:creator><![CDATA[Miguel Ponce G]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 14:51:20 GMT</pubDate>
            <atom:updated>2024-06-26T13:45:23.030Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article you will learn how to implement GraphQL using Hot Chocolate in an ASP.NET Core Web API built on the .NET 6 framework. <br>I had explain a little about GraphQL and its advantages in <a href="https://medium.com/@miguelponceg87/graphql-a-query-language-for-apis-eff687fc74c0"><strong>What is GraphQL</strong></a><strong>,</strong> you can check it out. <br>We are also going to take a look at the different GraphQL elements used to integrate GraphQL in our ASP.NET Core Web API.</p><h3><strong>Introduction</strong></h3><p>HotChocolate is a .NET GraphQL platform that can help you build a GraphQL layer over your existing and new application. HotChocolate is very easy to set up and takes the clutter away from writing GraphQL schemas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*pasE9bX1j6T7BjZ245EfhA.png" /></figure><p>We will create a simple application that will have a CRUD of products and get the information of the order detail of a Technology Store online</p><h3><strong>Repository</strong></h3><p>The code for this sample can be found on the <a href="https://github.com/MPonceG/GraphQLNetCoreHotChocolate.git">MPonceG/GraphQLNetCoreHotChocolate</a> repository on GitHub.</p><h3><strong>Prerequisites</strong></h3><p>Visual Studio 2022 (version 17.0.0 upwards)</p><p>SQL Server 2019</p><h3><strong>The Database</strong></h3><p>The database schema and data script can be found in the folder MPonceG/GraphQLNetCoreHotChocolate/Scripts. Ensure to run the script in SQL Server Management Studio or in Visual Studio SQL Server Object Explore to set up the Database and tables.</p><ol><li><strong>Create ASP.NET Core Web API from Template<br></strong>Open Visual Studio (I use version 2022) as developing with the .NET 6 framework. Create a new project, select ASP.NET Core Web API as the template, and give it a name you like.</li><li><strong>Install Dependencies<br></strong>We need to install the HotChocolate.AspNetCore(v12.15.2) package. The package contains the GraphQL API’s for ASP.NET. To install the package, right click the solution in the solution explorer and select Manage NuGet Packages for Solution. Under the Browse section, search for HotChocolate.AspNetCore and click on it, then in the preview panel click the Install button:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PL8n-BMRXXwrGXVt" /></figure><p>Also, install the <strong>Microsoft.EntityFrameworkCore</strong> and <strong>Microsoft.EntityFrameworkCore.SqlServer</strong> packages respectively.</p><p><strong>3. Add Models/Entities<br></strong>We will make use of EntityFrameworkCore as the ORM. Models/Entities (classes) are used to define the database objects (tables) and those models are mapped to the database table in the DbContext.</p><p>We will define four Models, one for the Accounts, another for Products, another for the Order and the other for the Order Details tables.</p><p>We will keep everything simple by using folders to hold the data access code, the GraphQL code and the Database Entities. In a real application, a Class library would be better for the different layers.</p><p>Create a folder called Models in the GraphQLHotChocolate project.</p><p><strong>Account Model</strong><br>Add a C# Class file called Account.cs to the Models folder. This class will be used to define the Account model. The code for this file is:</p><pre>using System.ComponentModel.DataAnnotations;<br>namespace GraphQLHotChocolate.Models<br>{<br>#nullable disable warnings<br>    public class Account<br>    {<br>        [Key]<br>        public int AccountId { get; set; }<br>        public string AccountEmail { get; set; }<br>        public string? AccountPassword { get; set; }<br>        public string? AccountFirstName { get; set; }<br>        public string? AccountLastName { get; set; }<br>        public string? AccountPhone { get; set; }<br>        public DateTime AccountDate { get; set; }<br>        public bool AccountStatus { get; set; }<br>    }<br>}</pre><p><strong>Order Model<br></strong>Add a C# Class file called Order.cs to the Models folder. This class will be used to define the Order model. The code for this file is:</p><pre>using System.ComponentModel.DataAnnotations;<br>namespace GraphQLHotChocolate.Models<br>{<br>#nullable disable warnings<br>    public class Order<br>    {<br>        [Key]<br>        public int OrderId { get; set; }<br>        public decimal OrderAmount { get; set; }<br>        public string? OrderShipName { get; set; }<br>        public string? OrderShipAddress { get; set; }<br>        public string? OrderEmail { get; set; }<br>        public DateTime OrderDate { get; set; }<br>        public bool OrderStatus { get; set; }<br>        public int AccountId { get; set; }<br>        public Account Account { get; set; }<br>        public List&lt;OrderDetail&gt; orderDetails { get; set; }<br>    }<br>}</pre><p><strong>Order Detail Model<br></strong>Add a C# Class file called OrderDetail.cs to the Models folder. This class will be used to define the Order Detail model. The code for this file is:</p><pre>using System.ComponentModel.DataAnnotations;<br>namespace GraphQLHotChocolate.Models<br>{<br>#nullable disable warnings<br>    public class OrderDetail<br>    {<br>        [Key]<br>        public int OrderDetailId { get; set; }<br>        public decimal OrderDetailPrice { get; set; }<br>        public string? OrderDetailName { get; set; }<br>        public int OrderDetailQuantity { get; set; }<br>        public DateTime OrderDetailDate { get; set; }<br>        public bool OrderDetailStatus { get; set; }<br>        public int OrderId { get; set; }<br>        public Order Order { get; set; }<br>        public int ProductId { get; set; }<br>        public Product Product { get; set; }<br>    }<br>}</pre><p><strong>Product Model</strong><br>Add a C# Class file called Product.cs to the Models folder. This class will be used to define the Product model. The code for this file is:</p><pre>using System.ComponentModel.DataAnnotations;namespace GraphQLHotChocolate.Models<br>{<br>    public class Product<br>    {        [Key]<br>        public int? ProductId { get; set; }<br>        public string? ProductName { get; set; }<br>        public string? ProductDescription { get; set; }<br>        public string? ProductSku { get; set; }<br>        public decimal? ProductPrice { get; set; }<br>        public DateTime? ProductUpdateDate { get; set; }<br>        public bool? ProductStatus { get; set; }    }<br>}</pre><p><strong>4. Add the DbContext<br></strong>The DbContext will be simple and straightforward. In a real application, most of the database configurations are done in this file. Add a new C# Class file to the Data folder, name it StoreDbContext.cs. The code for this file is:</p><pre>using GraphQLHotChocolate.Models;<br>using Microsoft.EntityFrameworkCore;<br><br>namespace GraphQLHotChocolate.Data<br>{<br>#nullable disable warnings<br>    public class StoreDbContext: DbContext<br>    {<br>        public StoreDbContext(DbContextOptions&lt;StoreDbContext&gt; options) : base(options)<br>        {<br><br>        }<br><br>        public DbSet&lt;Product&gt; Product { get; set; }<br>        public DbSet&lt;Account&gt; Account { get; set; }<br>        public DbSet&lt;Order&gt; Order { get; set; }<br>        public DbSet&lt;OrderDetail&gt; OrderDetail { get; set; }<br>    }<br>}</pre><p><strong>5. Add repositories<br></strong>Next, we will write the layer that will send and receive data to and from the database. In the Data folder, add another folder called Repositories.</p><p><strong>Order Repository</strong><br>Add a C# class file called OrderRepository.cs to the Repositories folder:</p><pre>using GraphQLHotChocolate.Models;<br>using Microsoft.EntityFrameworkCore;<br><br>namespace GraphQLHotChocolate.Data.Repositories<br>{<br>    public class OrderRepository<br>    {<br>        private readonly StoreDbContext _storeDbContext;<br><br>        public OrderRepository(StoreDbContext dbContext)<br>        {<br>            _storeDbContext = dbContext;<br>        }<br><br>        public List&lt;Order&gt; GetAllOrderwithDetails()<br>        {<br>            return _storeDbContext.Order<br>                .Include(a =&gt; a.Account)<br>                .Include(o =&gt; o.orderDetails).ThenInclude(p =&gt; p.Product)<br>                .ToList();<br>        }<br>    }<br>}</pre><p><strong>Order Detail Repository<br></strong>Add a C# class file called OrderDetailRepository.cs to the Repositories folder:</p><pre>using GraphQLHotChocolate.Models;<br>using Microsoft.EntityFrameworkCore;<br><br>namespace GraphQLHotChocolate.Data.Repositories<br>{<br>    public class OrderDetailRepository<br>    {<br>        private readonly StoreDbContext _storeDbContext;<br><br>        public OrderDetailRepository(StoreDbContext dbContext)<br>        {<br>            _storeDbContext = dbContext;<br>        }<br><br>        public List&lt;OrderDetail&gt; GetAllOrderDetails()<br>        {<br>            return _storeDbContext.OrderDetail<br>                .Include(o =&gt; o.Order).ThenInclude(a =&gt; a.Account)<br>                .Include(p =&gt; p.Product)                 <br>                .ToList();<br>        }<br>    }<br>}</pre><p><strong>Product Repository<br></strong>Add a C# class file called ProductRepository.cs to the Repositories folder:</p><pre>using GraphQLHotChocolate.Models;<br>using Microsoft.EntityFrameworkCore;<br><br>namespace GraphQLHotChocolate.Data.Repositories<br>{<br>    public class ProductRepository<br>    {<br>        private readonly StoreDbContext _storeDbContext;<br>        public ProductRepository(StoreDbContext dbContext)<br>        {<br>            _storeDbContext = dbContext;<br>        }<br><br>        public List&lt;Product&gt; GetAllProducts()<br>        {<br>            return _storeDbContext.Product.ToList();<br>        }<br><br>        public Product GetProductbyId(int id)<br>        {<br>            return _storeDbContext.Product.Where(p =&gt; p.ProductId == id).FirstOrDefault();<br>        }<br><br>        public async Task&lt;Product&gt; CreateProduct(Product product)<br>        {<br>            product.ProductUpdateDate = DateTime.Now;<br>            await _storeDbContext.Product.AddAsync(product);<br>            await _storeDbContext.SaveChangesAsync();<br>            return product;<br>        }<br><br>        public async Task&lt;Product&gt; UpdateProduct(Product product)<br>        {<br>            var updateProduct = _storeDbContext.Product.Find(product.ProductId);<br>            if (updateProduct != null) <br>            {<br>                updateProduct.ProductName = product.ProductName ?? updateProduct.ProductName;<br>                updateProduct.ProductDescription = product.ProductDescription ?? updateProduct.ProductDescription;<br>                updateProduct.ProductSku = product.ProductSku ?? updateProduct.ProductSku;<br>                updateProduct.ProductPrice = product.ProductPrice ?? updateProduct.ProductPrice;<br>                updateProduct.ProductUpdateDate = DateTime.Now;<br>                updateProduct.ProductStatus = product.ProductStatus ?? updateProduct.ProductStatus;<br>                _storeDbContext.Product.Update(updateProduct);<br>                await _storeDbContext.SaveChangesAsync();<br>            }<br>            <br>            return updateProduct;<br>        }<br><br>        <br>    }<br>}</pre><p><strong>6. Adding GraphQL<br></strong>If you are familiar with the REST API, we use GET to fetch data from the data store, we use POST, PUT DELETE to modify the state of data. GET in REST API is the same as Query in GraphQL. POST, PUT, DELETE, is the same as Mutation. In GraphQL, there is also Subscription which is used to set up event listeners.</p><p><strong>7. Adding Query<br></strong>Add a new C# class file called Query.cs to the GraphQL folder inside the Data folder. This class will contain all the Queries we need to perform:</p><pre>using GraphQLHotChocolate.Data.Repositories;<br>using GraphQLHotChocolate.Models;<br>using HotChocolate.Subscriptions;<br><br>namespace GraphQLHotChocolate.Data.GraphQL<br>{<br>    public class Query<br>    {<br>        public List&lt;Product&gt; GetAllProducts([Service] ProductRepository productRepository)<br>        {<br>            return productRepository.GetAllProducts();<br>        }<br><br>        public async Task&lt;Product&gt; GetProductbyId([Service] ProductRepository productRepository, <br>            [Service] ITopicEventSender eventSender, int id)<br>        {<br>            Product product = productRepository.GetProductbyId(id);<br>            await eventSender.SendAsync(&quot;ReturnedProduct&quot;, product);<br>            return product;<br>        }<br>        public List&lt;OrderDetail&gt; GetAllOrderDetails([Service] OrderDetailRepository orderDeatilRepository)<br>        {<br>            return orderDeatilRepository.GetAllOrderDetails();<br>        }<br><br>        public List&lt;Order&gt; GetAllOrderwithDetails([Service] OrderRepository orderRepository)<br>        {<br>            return orderRepository.GetAllOrderwithDetails();<br>        }<br>    }<br>}</pre><p><strong>8. Adding Mutation<br></strong>Add a new C# class file called Mutation.cs to the GraphQL folder inside the Data folder. This class will contain all the Mutations we need to perform:</p><pre>using GraphQLHotChocolate.Data.Repositories;<br>using GraphQLHotChocolate.Models;<br>using HotChocolate.Subscriptions;<br><br>namespace GraphQLHotChocolate.Data.GraphQL<br>{<br>    public class Mutation<br>    {<br>        public async Task&lt;Product&gt; CreateProduct([Service] ProductRepository productRepository, <br>            [Service] ITopicEventSender eventSender, Product product)<br>        {<br>            var newProduct = await productRepository.CreateProduct(product);<br>            await eventSender.SendAsync(&quot;AddProduct&quot;, newProduct);<br>            return newProduct;<br>        }<br><br>        public async Task&lt;Product&gt; UpdateProduct([Service] ProductRepository productRepository, Product product)<br>        {<br>            var updateProduct = await productRepository.UpdateProduct(product);<br>            return updateProduct;<br>        }<br>    }<br>}</pre><p><strong>9. Adding Subscription<br></strong>Subscriptions are used to set up event listeners e.g. we can set up an event listener that responds when we create a new Product or Query the database for a Product etc. Add a new C# class file called Subscription.cs to the GraphQL folder inside the Data folder:</p><pre>using GraphQLHotChocolate.Models;<br>using HotChocolate.Execution;<br>using HotChocolate.Subscriptions;<br><br>namespace GraphQLHotChocolate.Data.GraphQL<br>{<br>    public class Subscription<br>    {<br>        [SubscribeAndResolve]        <br>        public async ValueTask&lt;ISourceStream&lt;Product&gt;&gt; OnProductGet([Service] ITopicEventReceiver eventReceiver,<br>            CancellationToken cancellationToken)<br>        {<br>            return await eventReceiver.SubscribeAsync&lt;string, Product&gt;(&quot;ReturnedProduct&quot;, cancellationToken);<br>        }<br><br>        [SubscribeAndResolve]<br>        public async ValueTask&lt;ISourceStream&lt;Product&gt;&gt; OnProductAdd([Service] ITopicEventReceiver eventReceiver,<br>            CancellationToken cancellationToken)<br>        {<br>            return await eventReceiver.SubscribeAsync&lt;string, Product&gt;(&quot;AddProduct&quot;, cancellationToken);<br>        }<br>    }<br>}</pre><p><strong>10. Configuring GraphQL<br></strong>We need to configure the application to make use of GraphQL. Replace the code in your Program.cs with:</p><pre>using GraphQLHotChocolate.Data;<br>using GraphQLHotChocolate.Data.GraphQL;<br>using GraphQLHotChocolate.Data.Repositories;<br>using Microsoft.EntityFrameworkCore;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Add services to the container.<br>builder.Services.AddScoped&lt;OrderRepository, OrderRepository&gt;();<br>builder.Services.AddScoped&lt;OrderDetailRepository, OrderDetailRepository&gt;();<br>builder.Services.AddScoped&lt;ProductRepository, ProductRepository&gt;();<br><br>builder.Services.AddControllers();<br>// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>builder.Services.AddDbContext&lt;StoreDbContext&gt;(opt =&gt;<br>opt.UseSqlServer(builder.Configuration.GetConnectionString(&quot;TheStoreDB&quot;)));<br><br>builder.Services.AddGraphQLServer()<br>    .AddQueryType&lt;Query&gt;()<br>    .AddMutationType&lt;Mutation&gt;()<br>    .AddSubscriptionType&lt;Subscription&gt;()<br>    .AddInMemorySubscriptions();<br><br>var app = builder.Build();<br><br>// Configure the HTTP request pipeline.<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseHttpsRedirection();<br><br>app.UseAuthorization();<br><br>app.UseWebSockets();<br>app.MapGraphQL();<br><br>app.MapControllers();<br><br>app.Run();</pre><p>Line 21 is used to add the Service for GraphQL, Query, Mutation and Subscription. The AddQueryType(), AddMutationType() and AddSubscriptionType() takes in the Query, Mutation and Subscription classes respectively.</p><p>Line 39 is used to map the endpoint to GraphQL.</p><p>Line 18 adds the DbContext service; we configure this service to make use of SQL Server as the database. The connection string is defined in the appsettings.json file as:</p><pre>{<br>  &quot;Logging&quot;: {<br>    &quot;LogLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;<br>    }<br>  },<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;TheStoreDB&quot;: &quot;Data Source=localhost;Initial Catalog=TheStoreDB;Integrated Security=True;Trusted_Connection=True;Encrypt=False&quot;<br>  },<br>  &quot;AllowedHosts&quot;: &quot;*&quot;<br>}</pre><p><strong>11. Running the Application<br></strong>Right-click the solution and click Build Solution. After Build is successful, click CTRL + f5 or f5 to run the application. In your browser, navigate to <a href="https://localhost:7130/graphql/,">https://localhost:7130/graphql/,</a> you should get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*ngZUe6tTx8cwO9D6" /><figcaption>Operations available on the project: Query, Mutation and Subscription</figcaption></figure><p>HotChocolate gives you a GraphQL IDE (Banana Cake Pop) right in your browser out of the box, you don’t need to install any GraphQL IDE.</p><p>The methods defined in Query.cs, Mutation.cs and Subscription.cs have been categorized under Query, Mutation and Subscription respectively.</p><h3>Test Query</h3><p>In Banana cake pop, you can add a new tab by clicking the + in the top right corner of the IDE. You can run your schema by clicking the Execute/Play button in the top right corner. Add and run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/0*8LH510Xe-sf5gpiT" /><figcaption>Structure of the query allOrderwithDetails</figcaption></figure><p>You should get the response in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*UHMdopj0wFH6lOgYVzDelg.png" /><figcaption>Response of the query allOrderwithDetails</figcaption></figure><p>Try out other Query types, defining the Schema of the data you need.</p><h3>Test Subscription and Query</h3><p>Add and run the schema below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/0*GnatSUWX6lCJYQEw" /><figcaption>Structure of the subscription onProductGet</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*-B816BxzI4zGYKIYP_zfZQ.png" /><figcaption>Logs of the subscription onProductGet</figcaption></figure><p>This Subscribes to the event “ReturnedProduct” in line 13 of Subscription.cs. You won’t get any output yet as shown in the image above, but you can see from the console that we have Subscribed to the event.</p><p>Launch <a href="https://localhost:44351/graphql/">https://localhost:7130/graphql/</a> in another browser tab. Next, we will run a Query that will trigger the event. Add and run the below in a new Banana Cake Pop tab in the new browser tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*nBSWUn35ZIR8NX9Biw7-9g.png" /><figcaption>Structure of query productbyId</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*okDW_YJ3D7jWppdY76baVA.png" /><figcaption>Response of the query productbyId</figcaption></figure><p>If you go back to the first browser tab where we subscribed to the event, you will get the response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*l0AqWp1kmY__vRaLyGGXOg.png" /><figcaption>Response of the subscription onProductGet</figcaption></figure><p>If you change the value of the id and run the Query, you will see the changes in the Subscription.</p><h3>Test Mutation</h3><p>Add and run the schema below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*KM63tdaa7AEWAjKaRtL9oQ.png" /><figcaption>Structure to build a mutation and the body of product</figcaption></figure><p>You would get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*nxNrtQFQEF0IOGXEcoqeTQ.png" /><figcaption>Response of mutation createProduct</figcaption></figure><p>GraphQL is a very nice way to expose an API to the public. It makes it easier for the clients to get just the data they need. We now have a full ASP.NET Core Web API with GraphQL using HotChocolate with Query, Mutation and Subscription. It’s easy and offers a nice and easy way to interact with your application through the API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a30b57b8a989" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globallogic-latam/how-to-implement-graphql-in-asp-net-core-web-api-net-6-using-hotchocolate-a30b57b8a989">How to implement GraphQL in ASP.Net Core Web API (.NET 6) using HotChocolate</a> was originally published in <a href="https://medium.com/globallogic-latam">GlobalLogic LatAm</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL — A query language for APIs]]></title>
            <link>https://medium.com/globallogic-latam/graphql-a-query-language-for-apis-eff687fc74c0?source=rss-43996289094b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eff687fc74c0</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Miguel Ponce G]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 14:16:45 GMT</pubDate>
            <atom:updated>2024-06-19T11:49:52.176Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>GraphQL — A query language for APIs</strong></h3><h3>What is GraphQL?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Iaxcrrd6s7t8WaOy" /><figcaption>Some features about GraphQL</figcaption></figure><p>GraphQL is an open-source query and manipulation language for APIs developed by Facebook in 2012. Contrary to REST architecture, GraphQL is not an API specification; it’s a runtime for fulfilling queries with existing data. Backbend GraphQL provides a type system that describes a schema for data; in return, this gives front-end API consumers to request the exact data they need.</p><h3>GraphQL vs REST</h3><p>GraphQL is a query language. When developing our code, we define a type that GraphQL can use to query against. The awesome thing about GraphQL is that it adapts to the code and data at the client’s end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*VAMp65g_OeIw4yrlDMAg1w.png" /></figure><ul><li>GraphQL can provide customers with the exact data they need. One of the most common problems with traditional REST APIs is that they tend to cause over fetching, obtaining more information than needed. A REST query will extract all the data from a specific resource, while GraphQL will only get what is dictated in a query.</li><li>There is no specific programming language or database that has to be used for this to work.When utilizing GraphQL we minimize the number of roundtrips made from the client to the server to get all required data. When we use REST we have to visit a specific endpoint to get the data we need, as there is an action made inside a controller to serve just that data.</li><li>One thing that can be confusing about big applications using REST is the number of endpoints (it can be enormous)… by using GraphQL we can eliminate that as we only have one endpoint.</li><li>Another great thing about GraphQL is that you only get what you ask for. You won’t get a lot of data that you don’t need? How is that — well the reason is that a GraphQL query is defined by fields that you would like returned.</li></ul><blockquote>Like this example:<br>We want to get the information of an order detail, but we need to know the information of the products, the account of the user and the order amount final, to do this we can build a query.</blockquote><pre>query{<br>  allOrderDetails{<br>    orderDetailId<br>    orderDetailName<br>    orderDetailQuantity<br>    product {<br>      productName<br>      productDescription<br>      productSku<br>      productStatus<br>    }<br>    order {<br>      orderId<br>      orderAmount<br>      orderShipName<br>      orderEmail<br>      orderStatus<br>      account {<br>        accountFirstName<br>        accountLastName<br>        accountEmail<br>        accountStatus<br>      }<br>    }<br>    <br>  }<br>}</pre><p>This would produce the following response:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;allOrderDetails&quot;: [<br>      {<br>        &quot;orderDetailId&quot;: 1,<br>        &quot;orderDetailName&quot;: &quot;Adding Mouse Wireless&quot;,<br>        &quot;orderDetailQuantity&quot;: 1,<br>        &quot;product&quot;: {<br>          &quot;productName&quot;: &quot;Mouse Wireless&quot;,<br>          &quot;productDescription&quot;: &quot;Lorem ipsum dolor sit amet, cUt enim ad minim  ea commodo consequl, sunt in culpa qui officia deserunt mollit anim id est laborum.&quot;,<br>          &quot;productSku&quot;: &quot;P001&quot;,<br>          &quot;productStatus&quot;: true<br>        },<br>        &quot;order&quot;: {<br>          &quot;orderId&quot;: 1,<br>          &quot;orderAmount&quot;: 720,<br>          &quot;orderShipName&quot;: &quot;Technologies From Home&quot;,<br>          &quot;orderEmail&quot;: &quot;email@email.com&quot;,<br>          &quot;orderStatus&quot;: true,<br>          &quot;account&quot;: {<br>            &quot;accountFirstName&quot;: &quot;Miguel&quot;,<br>            &quot;accountLastName&quot;: &quot;Ponce&quot;,<br>            &quot;accountEmail&quot;: &quot;miguel.ponce@mail.com&quot;,<br>            &quot;accountStatus&quot;: true<br>          }<br>        }<br>      },<br>      {<br>        &quot;orderDetailId&quot;: 2,<br>        &quot;orderDetailName&quot;: &quot;Adding Keyword Wireless&quot;,<br>        &quot;orderDetailQuantity&quot;: 1,<br>        &quot;product&quot;: {<br>          &quot;productName&quot;: &quot;Keyword Wireless&quot;,<br>          &quot;productDescription&quot;: &quot;Lorem ipsum dolor sit amet, cUt enim ad minim  ea commodo consequl, sunt in culpa qui officia deserunt mollit anim id est laborum.&quot;,<br>          &quot;productSku&quot;: &quot;P003&quot;,<br>          &quot;productStatus&quot;: true<br>        },<br>        &quot;order&quot;: {<br>          &quot;orderId&quot;: 1,<br>          &quot;orderAmount&quot;: 720,<br>          &quot;orderShipName&quot;: &quot;Technologies From Home&quot;,<br>          &quot;orderEmail&quot;: &quot;email@email.com&quot;,<br>          &quot;orderStatus&quot;: true,<br>          &quot;account&quot;: {<br>            &quot;accountFirstName&quot;: &quot;Miguel&quot;,<br>            &quot;accountLastName&quot;: &quot;Ponce&quot;,<br>            &quot;accountEmail&quot;: &quot;miguel.ponce@mail.com&quot;,<br>            &quot;accountStatus&quot;: true<br>          }<br>        }<br>      },<br>      {<br>        &quot;orderDetailId&quot;: 3,<br>        &quot;orderDetailName&quot;: &quot;Adding Charger Wireless&quot;,<br>        &quot;orderDetailQuantity&quot;: 1,<br>        &quot;product&quot;: {<br>          &quot;productName&quot;: &quot;Charger Wireless&quot;,<br>          &quot;productDescription&quot;: &quot;Lorem ipsum dolor sit amet, cUt enim ad minim  ea commodo consequl, sunt in culpa qui officia deserunt mollit anim id est laborum.&quot;,<br>          &quot;productSku&quot;: &quot;P009&quot;,<br>          &quot;productStatus&quot;: true<br>        },<br>        &quot;order&quot;: {<br>          &quot;orderId&quot;: 1,<br>          &quot;orderAmount&quot;: 720,<br>          &quot;orderShipName&quot;: &quot;Technologies From Home&quot;,<br>          &quot;orderEmail&quot;: &quot;email@email.com&quot;,<br>          &quot;orderStatus&quot;: true,<br>          &quot;account&quot;: {<br>            &quot;accountFirstName&quot;: &quot;Miguel&quot;,<br>            &quot;accountLastName&quot;: &quot;Ponce&quot;,<br>            &quot;accountEmail&quot;: &quot;miguel.ponce@mail.com&quot;,<br>            &quot;accountStatus&quot;: true<br>          }<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>The above request would not be possible to make with REST as the typical REST endpoint would return more or less data than you need and you then need to use the returned data to request another endpoint to build a full dataset. It depends on how the developers behind the API you are consuming have made the implementation on their end. This is a really important and different advantage of GraphQL. It is really beneficial if we want to share this API to many apps because they can use the exact fields that they really will need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eff687fc74c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/globallogic-latam/graphql-a-query-language-for-apis-eff687fc74c0">GraphQL — A query language for APIs</a> was originally published in <a href="https://medium.com/globallogic-latam">GlobalLogic LatAm</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>