Conf42 Python 2025 - Online

- premiere 5PM GMT

Building GraphQL Microservices Using FastAPI

Video size:

Abstract

FastAPI is a Python web framework built on top of the ASGI standard. The fusion of GraphQL and FastAPI emerges as a pivotal approach for constructing agile and scalable microservices.

Summary

Transcript

This transcript was autogenerated. To make changes, submit a PR.
Hi there, everyone. Good morning, good afternoon and good evening to everyone joining us from around the world for con 40 to 25 python track. We are super excited to have a talk on building GraphQL microservices using fast APA for the next few minutes, we'll be discussing on these two technologies that have gained significant traction in the past few years, GraphQL and fast APA. So these technologies simplify the process of building smarter and more efficient APS. So we'll explain what GraphQL is, why it's becoming so popular and how can you start using it. So GraphQL is an API specification created by Facebook designed to make APIs smarter and more efficient. FastAPI, on the other hand, is a high performance web framework for building APIs. So it's known for its speed, simplicity, and powerful asynchronous capabilities. So let's explore how this, powerful pair works together to deliver fast and flexible, APS solutions. And, before we start a little about us, maybe I'm Joseph. And I have jealous with me. we are both product engineers at U S T where we are building Strollby, a travel platform that helps people explore and plan their journeys. We have been working with GraphQL microservices in Python for some time, and we are also part of Tramantrum Python community based out of Kerala. and that's a little about us. Let's jump right into GraphQL. So what is GraphQL? GraphQL is a coding language for APIs. and the runtime that execute those queries using your existing data. Have you ever needed data from an API, but ended up with too much or too little? It's really frustrating, right? That's exactly the problem GraphQL solves. With GraphQL, you ask for exactly what you need, no extra data, no missing pieces. Think it like making a custom query for your API, just like how you query your database. The server processes your request and sends back only the data you specified, nothing more, nothing less. This means faster response, fewer API calls, and better performance. That's the power of GraphQL. Let's dive deeper and see how it works in real world applications. Let's begin by understanding how traditional REST APIs and why they sometimes struggle to meet the needs of modern applications. REST APIs are built around the idea of fixed endpoints for specific pieces of data. For example, if you want to fetch users information, you could send a request to slash users endpoint. each resource is tied to its own unique URL. And when you send a request, the server responds with all the data related to that resource. While this approach works well in many cases, it often has two main problems, underfetching and overfetching. Underfetching happens when a client needs multiple pieces of data, only one, get one at a time. For example, if you need both user details and their associate post. You could have made two separate requests, one to slash request slash users and another to slash post. This leads to extra network call and slower performance. Overfetching is the opposite problem. Let's say only you need only your user's name, but slash users endpoints inspect entire user object, including their address, email and other data you don't need. This waste bandwidth slows down your application and may cause inefficiency, especially for mobile devices on limited network. Since different clients like mobile application, web applications, and dashboards often have different design requirements, but REST APIs serve the same fixed response to all clients. For example, imagine a mobile application that requires only the user's first name for a simple display. While the web application might require both name and the address. For a detailed profile, since REST API returns a fixed data set, both the clients should receive the same response, even though one of them needs only a small part of the data. Here, it's the mobile application. Another major challenge is maintaining and scaling APIs. When new features are added, all the clients might still rely on the previous version of the API to avoid breaking existing applications. Developers often create multiple versions of the API with these challenges. Rust API has become harder to manage and inefficient, especially as applications grow. This is where GraphQL comes in. So let's see how GraphQL. This diagram shows how GraphQL act as a bridge between the front end and the back end, making data fetching efficient and flexible. On the left side, we have the front end, this could be a web application, mobile application, or any sort of client requesting the data. Instead of making multiple API calls like the rest, here the client sends a single request to the GraphQL endpoint, that is a single GraphQL endpoint at slash GraphQL. The front end defines exactly what the data it requires in a structured query. Before processing a request, the GraphQL checks the schema. Schema is a blueprint that defines the available data types and relationships. This schema act as a contract between the front end and the back end, ensuring the requests are valid. On the right side, we have the backend services, which might contain multiple APIs, databases, and multiple services. Unlike traditional APIs, GraphQL does not store data. It's act as a multiple layer that fetches the information from multiple sources like databases and APIs. For example, a query requesting user information, order history and recent transactions can have different sort of data requirements. Fetch, data, it fetches the data from the user database. It, receives the order information. in a different services or a different A. P. I. And also it gets a transaction info from a third party vendor. All this happens in a single request, reducing the network calls and improving the performance. Once GraphQL gathers the requested data, it contains everything into a structured JSON response and sends back to the front end. The client receives only the data what it asked for, making data fetching faster. optimized and more efficient. This is why GraphQL is a game changer. It's having a single entry point, flexible coding and optimized responses. So let's talk about the three main operations supported in GraphQL, GraphQL queries, mutations, and subscriptions. So these operations define how a client interacts with the GraphQL API. So let's talk about, queries. So queries are how we retrieve data from a GraphQL API. Think of them like making a request to the database, but instead of getting all, responses, all, object, we can choose exactly what we need to in this example, we are asking for a specific user with ID one instead of fitting the ender data. And like the rest, we are only requesting the two fields, first name and the last name. no extra data is being sent. Only the response of first name and, last name will be fed back to the front end from, the GraphQL server. So next we have, mutations. mutations are how we modify the data, whether it's creating, updating or deleting records. here is an example. We are creating a mutation named create post so we can, once the post is created, the server returns its value as the confirmation. If you want, we can also fetch other additional fields like the title of the post or content. So the best part, unlike we might require separate raw call for updated values in REST, GraphQL returns the newly created or modified values immediately in the request, in the same response. Thank you So the last one is subscriptions, so it allows real time communication between the clients and the server instead of requesting data manually, the client can subscribe to events and get automatic updates whenever new data is available. For example, here. The subscription on create listens for new data being created. Whenever a new post is created, the server automatically sends to the update, to the client, where, if it's subscribed to this topic or this, end point on create, which is a subscription. So this is great for, real time applications, like notifications. or dashboards. So unlike queries and mutations, which follow a request response model, subscriptions create a open connection between client and server making real time updates possible. So just to recap, queries lets us to fetch data efficiently, mutations lets us modify data and get the immediate response while subscriptions lets us listen for real time updates without constantly polling the server. So this is what makes GraphQL so powerful. It gives the front end the full control over the data and making it efficient and flexible. Next is GraphQL Schema. So think of GraphQL Schema as the blueprint of your API. It defines the types, fields, and relationships that are available to the client. The schema uses schema definition language SDL to describe the data. Let's start with a simple example, a user type. In GraphQL, we use the type keyword to define the data structure. Here is how we define a user type in our schema. ID, which is a unique identifier for the user and followed by exclamation, which shows the field is record ID and both name, email are both record and having string, data state. So now, whenever we refer to a user in our GraphQL API, We know exactly what data it contains based out of this schema type. So next, if you want to create a query to allow us to fetch a user information, here it's get field, get user query. It takes ideas and argument. it returns the user object matching that I. D. So clients can request specific fields from the user object. And, next we have a mutation. So if you want to update the user's name, so we can use update user name mutation, which takes idea and the new name. And it returns, the updated name. So next, we can see the difference between GraphQL and REST API. So with the separate endpoint for, getting user info in REST, rather than a single endpoint GraphQL, and we can use separate query for getting, each fields. Of based out of the schema in GraphQL and we got the entire payload in the REST response while the requested fields are only fetched from DB or the other source of data in the response of GraphQL. One of the simplest ways to understand GraphQL versus Rust is comparing it to ordering a burger at a restaurant. So imagine we are walking into a restaurant with a fixed menu. The menu offers predefined burger options with fixed ingredients and you must order the ender burger even if you want only a certain set of toppings. So you can take the ender classic burger with lettuce, tomatoes and cheese. No customization allowed. This is how the Rust works. APS work. And there are other set of restaurants where we can customize our burger. we can specify what exactly we need. we can set the burger toppings, and this is how the GraphQL works. So in this analogy, the waiter represents the GraphQL schema. The waiter provides the list of available toppings, just like GraphQL defining, types with available fields for the client. Instead of browsing the fixed menu, we can directly tell the better what exactly we want. So similarly, GraphQL schema of data available and client chooses which fields to request. So with GraphQL, we get only what we ask for, making it more efficient. And here the chef act as the GraphQL, resolvers at the server site, which only prepares what the client requested. So they will not add any extra arguments or any extra, resolvers will be acted, for unnecessary data. And, we don't need multiple orders. Everything will be handled in a single request. So that's how GraphQL versus Rust is explained in LM and Tense. Moving on to GraphQL Python Ecosystem. There are multiple libraries available for GraphQL support within Python. When working with GraphQL, there are two main approaches for building your API. Code first and schema first. Each approach has its own set of libraries that help developers to implement GraphQL APIs efficiently. Code first approach allows developers to define their GraphQL schema using Python code. Instead of writing the STL, code first approach allows developers to define their GraphQL schema using Python code. you can define types and resolvers directly in Python using class and functions. So this approach is great for developers who prefer working within the Python ecosystem without writing any extra schema files. So graphene and strawberry are examples of code first and, in the schema fetch approach, GraphQL schema is written separately using STL and the schema act as a blueprint and resolvers are implemented in Python to handle this logic. This approach is beneficial for teams that want clear separation between the schema and the business backend logic. So now, moving on to Jayalashmi, for adding the essence of FastAPI to GraphQL. So moving to the next topic, that is FastAPI. Let me ask you something, what if we could build APIs that are not just super fast, but also super easy to develop, maintain, and scale? that's where FastAPI comes into play. FastAPI is the high performance Python framework that's built for real world demanding applications. So at its core, it runs on Starlet, a lightweight but powerful ASCII framework that it gives all the speed and reliability that you want to start developing. But here's the fun part. FastAPI takes Python type hints and turns them into something way more powerful. It's not just about a clean code, but a smarter code. So with the type hints and Python link working in the background, you get automatic validation, error handling, and even interactive documentation. Basically, everything a developer dreams of happening as you write your code. So why I'm so excited about this? Because FastAPI doesn't just stop at building great APIs. When you pair it with GraphQL, it becomes the ultimate tool for building modern, scalable microservices. So let's get into it. So moving on to the next slide, we have The key components are the core components of FastAPI, which makes it a high performance framework. So we could find that at its core, we have the Starlet, which serves as the foundational ASCII framework responsible for handling, routing, middleware, and concurrency. So it ensures that FastAPI operates efficiently and reliably. Next, we have the Python link on the other side, which is one of the most critical components that it handles the data validation, serialization, and parsing. By leveraging the Python's type hint, Python ensures that incoming data is validated automatically, reducing the risk of errors and enhancing code quality. So it also integrates with the uvconn, we know, like it's a fast ASCII server which ensures that optimal performance in handling concurrent requests. Also been powered by the uv loop and uvcon accelerates asynchronous operations, resulting in faster response times and improved scalability. So finally, these components are all powered by the compiled Python, the SciDun, and it forms the backbone of fastAPI's execution environment. this comes the core components and these all components work together to de To get FastAPI robust, scalable, and efficient framework for building modern APIs. So now moving to the next topic that is features of FastAPI. So the first one is the speed and developers friendly. And as we said in the beginning, FastAPI is one of the fastest. Frameworks Anavicon. And with Python type hints and Pythontic, it significantly boosts developer predictivity, making coding smoother. And next one is based on OpenAPI and JSON Schema. FastAPI automatically generates OpenAPI specifications and JSON Schema documentation for APIs. providing industry standard way to describe and interact with your endpoints. Next comes, the documentation, automatic documentation, and it generates interactive, API documentation using Swagger, UI, and etc. So it makes it easier for developers to explore and test the API directly from the browser. So next one is the asynchronous support. FastAPI is designed to fully support asynchronous programming, like allowing your application to handle concurrent tasks efficiently and improving scalability. So next one is data validation. So Pythonic ensures that all the data, like whether it's incoming or outgoing, it's automatically validated, preventing many common errors before they could even happen. And FastAPI also excels in path operations, like allowing you to define your API endpoints with clear, concise syntax. When it comes to security features, we have, it, it. It provides built in supports like JWT and other authentication protocols, making it simple to implement secure APIs. And dependency engine is another key feature, allowing you to manage and ensure dependencies with ease, promoting clean and integrable code. And the last one, middleware feature, like it, help us to add our custom functionality to your applications, like logging, authentication, or session management. That's it. without cluttering the core logic. So all these features collectively make this fast API comprehensive framework for building fast, secure, and scalable APIs. So let's move to the next slide. So now we can visualize the flow of how fast API integrates with GraphQL and the surrounding components. So at the center, we have the fast API GraphQL server, which acts as the backbone for your application. So it handles all the GraphQL queries, process them and return the corresponding responses. So the GraphQL list is on the top of FastAPI, where the client sends the queries and mutations to interact with the API. The FastAPI process these requests and through the GraphQL server resolves the queries by fetching the data from your underlying data sources. So the client side Whether it's a web application or a mobile app, the client sends GraphQL queries or mutations, usually over HTTP or web sockets to interact with the FastAPI server. And as Aby has already said that in the previous slide, this is exactly where GraphQL shines, that providing clients with a flexible and efficient way. to request exactly the data they need. So at the bottom flow, we have the database and FastAPI interacts with the database to create modified data based on the GraphQL queries. And we know, as I have already told, FastAPI is seamless asynchronous support. And this ensures that these databases interact happening quickly and efficiently, making it scalable for modern applications. So this flow illustrates how FastAPI and GraphQL come together to create Powerful, flexible, and scalable microservice architecture. So now let's see an example of GraphQL with FastAPI. So at the top, we can see the importing dependencies, and we are using here Graphin, which is a library used for creating the GraphQL schema and defining types. And uvicorn lightning fast as a server to run the FastAPI application. Also the FastAPI, the framework we are using here. Thanks so much. And the Starlet Graphene 3, it's a package providing the integration between GraphQL and FastAPI. And PostType class using Graphene. ObjectType. And this represents the structure of the data we are exposing through GraphQL. So here we have seen, the ID field, which is, of ID type, which is unique to each post. And the title and the summary fields are also using GraphQL. Here, and they are using string types, both marked as required. So here's the beauty of GraphQL. You can precisely define what your API will return, making it both predictable and flexible. So next step, we are adding a query. We create a query class, which is essentially the entry point for our GraphQL API. So we define a field called post, which allows clients to fetch data about a specific And the result function, that is, resultPost handles how the data is retrieved when a client makes a query. In this example, we return a hardcoded post type object, but in real world scenarios, this is where you would interact with your database or surveys to fetch the data. towards the end, we are integrating with the FastAPI. We build the GraphQL schema using graphene. schema and pass the query as it is. The root query, and then using the GraphQL app from start of the graphing GraphQL endpoint that is slash GraphQL into our FastAPI. And this is how FastAPI and GraphQL are seamlessly connected. On running the application, let's see what will be the output. you can see we are using the post service, you can see on the top left side, and also the endpoint slash GraphQL. GraphQL, and that's the query we are using that is posed in that we are asking for ID title and summary. And on the other side, we couldn't find the response, which is a structured and predictable response we are getting. So this is a simple, very simple example of GraphQL with fast API. So next we could move to the next slide. So now let's talk about GraphQL Federation, a powerful approach for scaling GraphQL APIs. Thanks. at its core, GraphQL Federation allows you to combine multiple GraphQL APIs, like each representing a distinct service, into a single unified graph. This means that no matter how many services you have, your clients can interact with all of them through a single entry point. what's so exciting about is that instead of managing complex client side logic for combining data from different services, the federated graph handles it for you. The router efficiently directs requests to the appropriate services, fetches the required data, and assembles it to give the response. So now, taking a look at the diagram, you will see how various web and mobile applications interact with a single router. Behind the scenes, this router communicates with individual services like here was service A, B, C, let it be user, post or anything like that, ensuring that everything works as a quasi system. So with GraphQL federation, scaling your microservice architecture becomes not just easier, but smarter. So let's see an example in the next slide. So now let's see an example for GraphQL federation. We could see a schema here and three services, post service, review service, and user service. At a schema of type post, we have title, which belongs to the post service, reviews belong to another service called review service, and author, which belongs to another service called user service. So this is exactly how the GraphQL Federation works. That is. We don't need to duplicate data or write extra logic to stitch them together. Each service defines only what it owns and the federation layer automatically resolves everything. let's see, the output, or just we can see the user's query and it can fetch the data if, even if it belongs to another service. this is how the GraphQL federation works and there's a lot more to learn in this, it's just a simple explanation. So thus, we come to the end of our slides. to wrap up things, today we explore GraphQL, its flexibility, efficiency, and how it changes the way we build APIs. We did so how FastAPI with its speed and developer friendly features make integrating GraphQL even more powerful. And finally, we dive into GraphQL Federation, where multiple microservices comes together to form a unified API. So with all these tools, we are not just building APIs, we are architecting the scalable, efficient, and future ready microservices. So thank you all for your time and attention. Keep exploring, stay curious, and keep building amazing things. Stay updated and let's continue learning together. Thank you.
...

Aby M Joseph

Product Engineer @ UST

Aby M Joseph's LinkedIn account Aby M Joseph's twitter account

Jayalekshmi K S

Product Engineer @ UST



Join the community!

Learn for free, join the best tech learning community for a price of a pumpkin latte.

Annual
Monthly
Newsletter
$ 0 /mo

Event notifications, weekly newsletter

Delayed access to all content

Immediate access to Keynotes & Panels

Community
$ 8.34 /mo

Immediate access to all content

Courses, quizes & certificates

Community chats

Join the community (7 day free trial)