#graphql example spring boot
Explore tagged Tumblr posts
codeonedigest · 2 years ago
Text
Why to Use Graphql Explained with Example for API Developers
Full Video Link - https://youtube.com/shorts/hO2vbzF4cNk Hi, a new #video on #graphql usage for #microservice #api #developers is published on #codeonedigest #youtube channel. @java #java #awscloud @awscloud #aws @AWSCloudIndia #Cloud #CloudComp
GraphQL is a syntax for requesting data. It’s a query language for APIs. It lets you specify exactly what is needed, and then it fetches just that — nothing more, nothing less. GraphQL is the solutions to common REST issues like over fetching and multiple network request. REST is an API design architecture that has become the norm for implementing web services.  It uses HTTP to get data and…
Tumblr media
View On WordPress
0 notes
sathcreation · 23 days ago
Text
Full Stack Web Development Coaching at Gritty Tech
Master Full Stack Development with Gritty Tech
If you're looking to build a high-demand career in web development, Gritty Tech's Full Stack Web Development Coaching is the ultimate solution. Designed for beginners, intermediates, and even experienced coders wanting to upskill, our program offers intensive, hands-on training. You will master both front-end and back-end development, preparing you to create complete web applications from scratch For More…
At Gritty Tech, we believe in practical learning. That means you'll not only absorb theory but also work on real-world projects, collaborate in teams, and build a strong portfolio that impresses employers.
Why Choose Gritty Tech for Full Stack Coaching?
Gritty Tech stands out because of our commitment to excellence, personalized mentorship, and career-oriented approach. Here's why you should choose us:
Expert Instructors: Our trainers are seasoned professionals from leading tech companies.
Project-Based Learning: You build real applications, not just toy examples.
Career Support: Resume workshops, interview preparation, and networking events.
Flexible Learning: Evening, weekend, and self-paced options are available.
Community: Join a vibrant community of developers and alumni.
What is Full Stack Web Development?
Full Stack Web Development refers to the creation of both the front-end (client-side) and back-end (server-side) portions of a web application. A full stack developer handles everything from designing user interfaces to managing servers and databases.
Front-End Development
Front-end development focuses on what users see and interact with. It involves technologies like:
HTML5 for structuring web content.
CSS3 for designing responsive and visually appealing layouts.
JavaScript for adding interactivity.
Frameworks like React, Angular, and Vue.js for building scalable web applications.
Back-End Development
Back-end development deals with the server-side, databases, and application logic. Key technologies include:
Node.js, Python (Django/Flask), Ruby on Rails, or Java (Spring Boot) for server-side programming.
Databases like MySQL, MongoDB, and PostgreSQL to store and retrieve data.
RESTful APIs and GraphQL for communication between client and server.
Full Stack Tools and DevOps
Version Control: Git and GitHub.
Deployment: AWS, Heroku, Netlify.
Containers: Docker.
CI/CD Pipelines: Jenkins, GitLab CI.
Gritty Tech Full Stack Coaching Curriculum
Our curriculum is carefully crafted to cover everything a full stack developer needs to know:
1. Introduction to Web Development
Understanding the internet and how web applications work.
Setting up your development environment.
Introduction to Git and GitHub.
2. Front-End Development Mastery
HTML & Semantic HTML: Best practices for accessibility.
CSS & Responsive Design: Media queries, Flexbox, Grid.
JavaScript Fundamentals: Variables, functions, objects, and DOM manipulation.
Modern JavaScript (ES6+): Arrow functions, promises, async/await.
Front-End Frameworks: Deep dive into React.js.
3. Back-End Development Essentials
Node.js & Express.js: Setting up a server, building APIs.
Database Management: CRUD operations with MongoDB.
Authentication & Authorization: JWT, OAuth.
API Integration: Consuming third-party APIs.
4. Advanced Topics
Microservices Architecture: Basics of building distributed systems.
GraphQL: Modern alternative to REST APIs.
Web Security: Preventing common vulnerabilities (XSS, CSRF, SQL Injection).
Performance Optimization: Caching, lazy loading, code splitting.
5. DevOps and Deployment
CI/CD Fundamentals: Automating deployments.
Cloud Services: Hosting apps on AWS, DigitalOcean.
Monitoring & Maintenance: Tools like New Relic and Datadog.
6. Soft Skills and Career Coaching
Resume writing for developers.
Building an impressive LinkedIn profile.
Preparing for technical interviews.
Negotiating job offers.
Real-World Projects You'll Build
At Gritty Tech, you won't just learn; you'll build. Here are some example projects:
E-commerce Website: A full stack shopping platform.
Social Media App: Create a mini version of Instagram.
Task Manager API: Backend API to handle user tasks with authentication.
Real-Time Chat Application: WebSocket-based chat system.
Each project is reviewed by mentors, and feedback is provided to ensure continuous improvement.
Personalized Mentorship and Live Sessions
Our coaching includes one-on-one mentorship to guide you through challenges. Weekly live sessions provide deeper dives into complex topics and allow real-time Q&A. Mentors assist with debugging, architectural decisions, and performance improvements.
Tools and Technologies You Will Master
Languages: HTML, CSS, JavaScript, Python, SQL.
Front-End Libraries/Frameworks: React, Bootstrap, TailwindCSS.
Back-End Technologies: Node.js, Express.js, MongoDB.
Version Control: Git, GitHub.
Deployment: Heroku, AWS, Vercel.
Other Tools: Postman, Figma (for UI design basics).
Student Success Stories
Thousands of students have successfully transitioned into tech roles through Gritty Tech. Some notable success stories:
Amit, from a sales job to Front-End Developer at a tech startup within 6 months.
Priya, a stay-at-home mom, built a portfolio and landed a full stack developer role.
Rahul, a mechanical engineer, became a software engineer at a Fortune 500 company.
Who Should Join This Coaching Program?
This coaching is ideal for:
Beginners with no coding experience.
Working professionals looking to switch careers.
Students wanting to learn industry-relevant skills.
Entrepreneurs building their tech startups.
If you are motivated to learn, dedicated to practice, and open to feedback, Gritty Tech is the right place for you.
Career Support at Gritty Tech
At Gritty Tech, our relationship doesn’t end when you finish the course. We help you land your first job through:
Mock interviews.
Technical assessments.
Building an impressive project portfolio.
Alumni referrals and job placement assistance.
Certifications
After completing the program, you will receive a Full Stack Web Developer Certification from Gritty Tech. This certification is highly respected in the tech industry and will boost your resume significantly.
Flexible Payment Plans
Gritty Tech offers affordable payment plans to make education accessible to everyone. Options include:
Monthly Installments.
Pay After Placement (Income Share Agreement).
Early Bird Discounts.
How to Enroll
Enrolling is easy! Visit Gritty Tech Website and sign up for the Full Stack Web Development Coaching program. Our admissions team will guide you through the next steps.
Frequently Asked Questions (FAQ)
How long does the Full Stack Web Development Coaching at Gritty Tech take?
The program typically spans 6 to 9 months depending on your chosen pace (full-time or part-time).
Do I need any prerequisites?
No prior coding experience is required. We start from the basics and gradually move to advanced topics.
What job roles can I apply for after completing the program?
You can apply for roles like:
Front-End Developer
Back-End Developer
Full Stack Developer
Web Application Developer
Software Engineer
Is there any placement guarantee?
While we don't offer "guaranteed placement," our career services team works tirelessly to help you land a job by providing job referrals, mock interviews, and resume building sessions.
Can I learn at my own pace?
Absolutely. We offer both live cohort-based batches and self-paced learning tracks.
Ready to kickstart your tech career? Join Gritty Tech's Full Stack Web Development Coaching today and transform your future. Visit grittytech.com to learn more and enroll!
0 notes
antonymarshall · 25 days ago
Text
Top 7 Skills to Become A Full-Stack Developer in 2025
With the ever-increasing pace of technological change, the need for techies with multidisciplinary skills has never been higher. One of the most sought-after jobs in the tech field today is that of a Full-Stack Developer̶ one who could smartly trick both front and back-end development. By 2025, this position promises to be even more dynamic and skill-intensive than before, requiring the developers to be multi-talented, flexible, and always learning. Thus, whether you are just stepping into this profession or you're enhancing your skill set, full stack web development entails mastering as many skills as possible to stay relevant.
Let us check out the top 7 crucial skills that every full-stack developer should develop by 2025. Front-End Expertise The user interface is the first thing people see and interact with--that's why we call this front-end work fundamental. A full-stack developer must have a good working knowledge of HTML, CSS, and JavaScript, the trifecta of front-end development. For 2025, developers who know tools like React.js, Vue.js, and Next.js are in ever-increasing demand, as these frameworks can be used to develop dynamic, highly performant, and mobile-responsive web applications. One should also know a little about aspects such as responsive design and various browser compatibilities. Grasping concepts related to state management on the front end (for example, using Redux, Zustand, or the React Context API) boosts one's professional profile, with companies recognizing these competencies.
Strong Back-End Knowledge While the front-end sees what the user gets, the back-end makes things run in the background. Full-stack developers should command the lease on server-side programming using languages such as JavaScript (Node.js), Python (Django/Flask), Java (Spring Boot), or Ruby on Rails. You would need to know how to build RESTful APIs and work with user sessions, authentication, and authorization with communications to a database. Keeping in mind the social aspect of security and data integrity, it is also important for any practice to involve the rest-audit trail, validation, error handling, etc. Knowledge of cloud platforms like AWS, Google Cloud, or Azure would be an added advantage for deploying a scalable back end.
Database Management Every full-stack developer must have some hardcore database skills. It doesn't matter if it is the relational database world of MySQL or PostgreSQL or the advanced NoSQL world of MongoDB, you need to know how to work with schema design, efficient query writing, and database connection management. In 2025, a developer must know the difference between structured and unstructured data and know when to use what type of database. Indexing, normalization, and transactions will become especially critical to you as you build scalable applications. ORMs (Object Relational Mappers) like Sequelize or Mongoose are also crucial for streamlining code/database interaction.
Understanding of APIs APIs (Application Programming Interfaces) are the glue that binds together the various pieces of a system. A full-stack developer should be able to build and consume APIs. Although REST is still the most-used tool, GraphQL has emerged as an alternative technology due to its speed and flexibility. To properly build and solve any API issues, an understanding of Postman or Insomnia as tools is necessary. Familiarity with authentication methods, such as OAuth2.0, JWT (JSON Web Tokens), and API key management, secures your applications while they communicate with the different services.
Version Control Working on software projects without version control is akin to tight-rope walking without a safety net. Developers can use Git tools to track changes or collaborate more efficiently and roll back to previous versions and full-stack developers should know Git well enough to create branches and merge code to resolve conflicts and manage pull requests. Beyond 2025, GitHub, GitLab, and Bitbucket will be more relevant to the work process of the teams. Apart from collaboration, knowing Git shows the power and the discipline in practice concerning coding.
Performance Optimization Your web app must not just work, but also work fast. Performance optimization is nowadays inevitable in an era where user experience rules. On the front ends, such performance optimization encompasses reduced render time, reduced bundle size, lazy loading of components, or using CDNs. Back-end-side optimizations include the use of caching systems such as Redis, optimization in database query usage, and using effective server-side rendering methodologies. A full-stack developer should know how to use performance monitoring tools, such as Lighthouse and Google Web Vitals, and also backend profiling tools to identify and resolve bottlenecks.
Problem-Solving & Soft Skills: While technical skills are backbone assets in development, soft skills with problem-solving capabilities do much more to separate the wheat from the chaff in talented developers. This also includes proficiency in debugging codes and high-level thinking with systematic approaches toward solving problems in everyday development. Just as essential are communication, working as a team, and working in an agile environment. More and more, employers are looking for people who work as teammates but can also adjust easily to keep pace with ever-changing requirements, while contributing positively to the dynamics of a team.
Take up a Course: If in 2025, you really want to be a Full-Stack Developer, going for a regular course is going to be an accelerator in your skills. Make sure you find one that comes with hands-on projects, industry tools, and mentorship from seasoned pros. The course should be extensive — everything from HTML and JavaScript to back-end programming and deployment. Practical experience is the name of the game; the course should emphasize building an entire web application from scratch.
Conclusion Being a full-stack developer in 2025 will entail much more than just coding: it means knowing how every part of a web application fits together-from the user interface to the database. Mastering the above-mentioned seven basic skills will ensure your position as a really well-capable and competitive developer in today's technology-enriched world.
0 notes
learning-code-ficusoft · 2 months ago
Text
A Guide to Creating APIs for Web Applications
Tumblr media
APIs (Application Programming Interfaces) are the backbone of modern web applications, enabling communication between frontend and backend systems, third-party services, and databases. In this guide, we’ll explore how to create APIs, best practices, and tools to use.
1. Understanding APIs in Web Applications
An API allows different software applications to communicate using defined rules. Web APIs specifically enable interaction between a client (frontend) and a server (backend) using protocols like REST, GraphQL, or gRPC.
Types of APIs
RESTful APIs — Uses HTTP methods (GET, POST, PUT, DELETE) to perform operations on resources.
GraphQL APIs — Allows clients to request only the data they need, reducing over-fetching.
gRPC APIs — Uses protocol buffers for high-performance communication, suitable for microservices.
2. Setting Up a REST API: Step-by-Step
Step 1: Choose a Framework
Node.js (Express.js) — Lightweight and popular for JavaScript applications.
Python (Flask/Django) — Flask is simple, while Django provides built-in features.
Java (Spring Boot) — Enterprise-level framework for Java-based APIs.
Step 2: Create a Basic API
Here’s an example of a simple REST API using Express.js (Node.js):javascriptconst express = require('express'); const app = express(); app.use(express.json());let users = [{ id: 1, name: "John Doe" }];app.get('/users', (req, res) => { res.json(users); });app.post('/users', (req, res) => { const user = { id: users.length + 1, name: req.body.name }; users.push(user); res.status(201).json(user); });app.listen(3000, () => console.log('API running on port 3000'));
Step 3: Connect to a Database
APIs often need a database to store and retrieve data. Popular databases include:
SQL Databases (PostgreSQL, MySQL) — Structured data storage.
NoSQL Databases (MongoDB, Firebase) — Unstructured or flexible data storage.
Example of integrating MongoDB using Mongoose in Node.js:javascriptconst mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true, useUnifiedTopology: true });const UserSchema = new mongoose.Schema({ name: String }); const User = mongoose.model('User', UserSchema);app.post('/users', async (req, res) => { const user = new User({ name: req.body.name }); await user.save(); res.status(201).json(user); });
3. Best Practices for API Development
🔹 Use Proper HTTP Methods:
GET – Retrieve data
POST – Create new data
PUT/PATCH – Update existing data
DELETE – Remove data
🔹 Implement Authentication & Authorization
Use JWT (JSON Web Token) or OAuth for securing APIs.
Example of JWT authentication in Express.js:
javascript
const jwt = require('jsonwebtoken'); const token = jwt.sign({ userId: 1 }, 'secretKey', { expiresIn: '1h' });
🔹 Handle Errors Gracefully
Return appropriate status codes (400 for bad requests, 404 for not found, 500 for server errors).
Example:
javascript
app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });
🔹 Use API Documentation Tools
Swagger or Postman to document and test APIs.
4. Deploying Your API
Once your API is built, deploy it using:
Cloud Platforms: AWS (Lambda, EC2), Google Cloud, Azure.
Serverless Functions: AWS Lambda, Vercel, Firebase Functions.
Containerization: Deploy APIs using Docker and Kubernetes.
Example: Deploying with DockerdockerfileFROM node:14 WORKDIR /app COPY package.json ./ RUN npm install COPY . . CMD ["node", "server.js"] EXPOSE 3000
5. API Testing and Monitoring
Use Postman or Insomnia for testing API requests.
Monitor API Performance with tools like Prometheus, New Relic, or Datadog.
Final Thoughts
Creating APIs for web applications involves careful planning, development, and deployment. Following best practices ensures security, scalability, and efficiency.
WEBSITE: https://www.ficusoft.in/python-training-in-chennai/
0 notes
korshubudemycoursesblog · 5 months ago
Text
Understanding GraphQL
Before diving into Spring GraphQL, it's essential to grasp what GraphQL is. Developed by Facebook in 2012, GraphQL is a query language for APIs that allows clients to request only the data they need. Unlike RESTful APIs, where the server defines the data structure, GraphQL enables clients to specify the exact data requirements, reducing over-fetching and under-fetching of data.
Key Features of GraphQL:
Declarative Data Fetching: Clients can request specific data, leading to optimized network usage.
Single Endpoint: All data queries are handled through a single endpoint, simplifying the API structure.
Strong Typing: GraphQL schemas define types and relationships, ensuring consistency and clarity.
Introducing Spring GraphQL
Spring GraphQL is a project that integrates GraphQL into the Spring ecosystem. It provides the necessary tools and libraries to build GraphQL APIs using Spring Boot, leveraging the robustness and familiarity of the Spring Framework.
Why Choose Spring GraphQL?
Seamless Integration: Combines the capabilities of Spring Boot with GraphQL, allowing developers to build scalable and maintainable APIs.
Auto-Configuration: Spring Boot's auto-configuration simplifies setup, enabling developers to focus on business logic.
Community Support: Backed by the extensive Spring community, ensuring continuous updates and support.
Setting Up a Spring GraphQL Project
To start building with Spring GraphQL, follow these steps:
1. Create a New Spring Boot Project
Use Spring Initializr to generate a new project:
Project: Maven Project
Language: Java
Spring Boot: Choose the latest stable version
Dependencies:
Spring Web
Spring for GraphQL
Spring Data JPA (if you're interacting with a database)
H2 Database (for in-memory database testing)
Download the project and import it into your preferred IDE.
2. Define the GraphQL Schema
GraphQL schemas define the structure of the data and the queries available. Create a schema file (schema.graphqls) in the src/main/resources/graphql directory:
graphql
Copy code
type Query {
    greeting(name: String! = "Spring"): String!
    project(slug: ID!): Project
}
type Project {
    slug: ID!
    name: String!
    repositoryUrl: String!
    status: ProjectStatus!
}
enum ProjectStatus {
    ACTIVE
    COMMUNITY
    INCUBATING
    ATTIC
    EOL
}
This schema defines a Query type with two fields: greeting and project. The Project type includes details like slug, name, repositoryUrl, and status. The ProjectStatus enum represents the various states a project can be in.
3. Implement Resolvers
Resolvers are responsible for fetching the data corresponding to the queries defined in the schema. In Spring GraphQL, you can use controllers to handle these queries:
java
Copy code
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;
@Controller
public class ProjectController {
    @QueryMapping
    public String greeting(String name) {
        return "Hello, " + name + "!";
    }
    @QueryMapping
    public Project project(String slug) {
        // Logic to fetch project details by slug
    }
}
In this example, the greeting method returns a simple greeting message, while the project method fetches project details based on the provided slug.
4. Configure Application Properties
Ensure your application properties are set up correctly, especially if you're connecting to a database:
properties
Copy code
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
These settings configure an in-memory H2 database for testing purposes.
5. Test Your GraphQL API
With the setup complete, you can test your GraphQL API using tools like GraphiQL or Postman. Send queries to the /graphql endpoint of your application to retrieve data.
Benefits of Using Spring GraphQL
Integrating GraphQL with Spring Boot offers several advantages:
Efficient Data Retrieval: Clients can request only the data they need, reducing unnecessary data transfer.
Simplified API Management: A single endpoint handles all queries, streamlining the API structure.
Strong Typing: Schemas define data types and relationships, minimizing errors and enhancing clarity.
Flexibility: Easily add or deprecate fields without impacting existing clients, facilitating smooth evolution of the API.
Conclusion
Spring GraphQL empowers developers to build flexible and efficient APIs by combining the strengths of GraphQL and the Spring Framework. By following the steps outlined above, you can set up a Spring GraphQL project and start leveraging its benefits in your applications
0 notes
subb01 · 6 months ago
Text
Essential Full Stack Development Interview Questions to Prepare For Your Next Job Opportunity
The demand for skilled full stack developers continues to grow as more companies seek professionals who can handle both the front-end and back-end development of applications. Preparing for a full stack development interview involves understanding a wide range of concepts that cover various technologies, frameworks, and programming practices.
To set yourself apart and confidently face interviews, consider exploring these essential full stack development interview questions. And for an insightful video overview of full stack interview preparation, check out this Full Stack Developer Interview Preparation Guide.
1. What is Full Stack Development?
Full stack development refers to the practice of working on both the front-end (client-side) and back-end (server-side) of a web application. A full stack developer is proficient in multiple technologies that enable them to build fully functional web applications from start to finish.
Key Points to Discuss:
Differences between front-end, back-end, and full stack development.
Advantages of hiring a full stack developer for a project.
2. What Are the Most Commonly Used Front-End Technologies?
Front-end development involves creating the user interface and ensuring a seamless user experience. The most popular front-end technologies include:
HTML: The standard markup language for creating web pages.
CSS: Used to style and layout web pages.
JavaScript: Essential for interactive features.
Frameworks/Libraries: React, Angular, and Vue.js.
Follow-Up Questions:
How do these technologies differ in terms of use cases?
Can you explain the benefits of using a front-end framework like React over vanilla JavaScript?
3. Explain the Role of Back-End Technologies in Full Stack Development.
The back-end of an application handles the server, database, and business logic. Key technologies include:
Node.js: A JavaScript runtime for server-side programming.
Express.js: A web application framework for Node.js.
Databases: SQL (e.g., MySQL, PostgreSQL) and NoSQL (e.g., MongoDB).
Other Languages: Python (Django, Flask), Ruby (Rails), and Java (Spring Boot).
Important Discussion Points:
RESTful services and APIs.
Authentication and authorization mechanisms (e.g., JWT, OAuth).
4. How Do You Ensure Code Quality and Maintainability?
Interviewers often ask this question to understand your approach to writing clean, maintainable code. Emphasize:
Version Control: Using Git and platforms like GitHub for collaborative coding.
Linting Tools: ESLint for JavaScript and other language-specific tools.
Code Reviews: The importance of peer reviews for improving code quality.
Best Practices: Following design patterns and SOLID principles.
5. Can You Discuss the MVC Architecture?
The Model-View-Controller (MVC) architecture is a common design pattern used in full stack development. Each part of the pattern has a distinct role:
Model: Manages data and business logic.
View: The user interface.
Controller: Connects the Model and View, handling input and output.
Why It’s Important:
Helps organize code, making it more scalable and easier to maintain.
Many frameworks, such as Django and Ruby on Rails, are built on MVC principles.
6. What Is REST and How Is It Used in Full Stack Development?
Representational State Transfer (REST) is an architectural style used to design networked applications:
Key Features: Stateless, cacheable, and uses standard HTTP methods (GET, POST, PUT, DELETE).
Implementation: Building RESTful APIs to enable communication between client and server.
Common Follow-Ups:
How do RESTful APIs differ from GraphQL?
Can you provide an example of designing a RESTful API?
7. Explain the Role of Databases and When to Use SQL vs. NoSQL.
Choosing between SQL and NoSQL depends on the application's needs:
SQL Databases: Structured, table-based databases like MySQL and PostgreSQL. Best for applications requiring complex queries and data integrity.
NoSQL Databases: Flexible, schema-less options like MongoDB and Cassandra. Ideal for handling large volumes of unstructured data.
Typical Questions:
What are the ACID properties in SQL databases?
When would you prefer MongoDB over a relational database?
8. How Do You Implement User Authentication?
User authentication is crucial for any secure application. Discuss:
Methods: Sessions, cookies, JSON Web Tokens (JWT).
Frameworks: Passport.js for Node.js, Auth0 for advanced solutions.
Best Practices: Storing passwords securely using hashing algorithms like bcrypt.
9. What Are Webpack and Babel Used For?
These tools are essential for modern JavaScript development:
Webpack: A module bundler for bundling JavaScript files and assets.
Babel: A JavaScript compiler that allows you to use next-gen JavaScript features by transpiling code to be compatible with older browsers.
Related Questions:
How do you optimize your build for production using Webpack?
What is tree shaking, and how does it improve performance?
10. How Do You Handle Error Handling in JavaScript?
Error handling is vital for ensuring that applications are resilient:
Try-Catch Blocks: For handling synchronous errors.
Promises and .catch(): For managing asynchronous operations.
Error Handling Middleware: Used in Express.js for centralized error management.
Important Concepts:
Logging errors and using tools like Sentry for real-time monitoring.
Creating user-friendly error messages.
Preparing thoroughly for full stack development interviews by understanding these questions will set you on the path to success. For a comprehensive walkthrough and additional insights, make sure to check out this YouTube guide, where these topics are discussed in detail to boost your interview readiness.
0 notes
tak4hir0 · 5 years ago
Link
こんにちは、エムスリー エンジニアリンググループ マルチデバイスチームの藤原です。 昨年末に医師向けのスマホアプリを新たにリリースしました。 スマホアプリ向けの BFF(Backends For Frontends) も新規に開発したのですが、そこには SpringBoot + Kotlin + GraphQL なアプリケーションを採用しています。 GraphQL はチームでの採用は初めてで、私もこのプロジェクトで初めて触りました。 その��うな状況だったので GraphQL 周りについては試行錯誤を重ねることとなったのですが、今回はその開発の中で見えてきた プラクティス をいくつか紹介したいと思います。 これから SpringBoot + Kotlin + GraphQL な開発をされる方の参考になれば幸いです。 ボネリークマタカ(某GraphQLの入門書*1の表紙にもこの鳥が描かれている) (Godbolemandar [CC BY-SA 4.0], ウィキメディア・コモンズより) スカラー型の入力チェックは Custom Scalar を使おう 認証結果は GraphQLContext に保存しよう ユーザ情報のフィールドにするべきものとそうじゃないもの 認証が必要であることは Directive で表現しよう エラーハンドリング フィールドで Nullable or Non-null を迷うようなら Nullable フィールドの引数で Nullable or Non-null を迷うようなら Non-null 要素追加の可能性がある Enum を使うときは細心の注意を 解決策1. unknown だった場合にどうするか決める 解決策2. フィールドを変える 解決策3. Enum を使わない 先人の知恵を借りる We are hiring ※ この記事に登場する graphql-java 依存のクラス等は以下のライブラリとバージョンを元にしています。 graphql-java 13.0 *2 graphql-java-servlet 8.0.0 *3 graphql-java-tools 5.6.1 *4 graphql-spring-boot-starter 5.10.0 *5 スカラー型の入力チェックは Custom Scalar を使おう GraphQL スキーマのフィールドには引数を渡すことができますが、実行時に入力チェックをしたい場合があります。 GraphQL クエリを発行すると対応するリ���ルバーが実行されるので、愚直にやるとリゾルバーで入力チェックのロジックを実装することになります。 以下��メッセージ一覧をページネーションで取得するスキーマとリゾルバーの例です。 type Query { # メッセージ一覧を取得する messages( # 取得件数 first: Int! # 指定した文字列が表すメッセージ以降を取得する after: String ): [Message!] } class QueryResolver : GraphQLQueryResolver { fun messages(first: Int { // first に100以上の数値が指定されたらエラーにしたい if 100) throw IllegalArgumentException() ... } } リゾルバーで取得件数の上限チェックを行なっていますが、他のリゾルバーでも同じような入力チェックを何回も実装しないといけなくなるかもしれず、あまりよくない匂いがします。 GraphQL では独自に任意のスカラー型を定義することができ、スカラー型に入力チェックを実装することでリゾルバーで入力チェックをする必要がなくなります。 スカラー型で入力チェックするようにした場合、スキーマとリゾルバーの実装は以下のようになります。 # ページネーション用の量指定型(1から99の数値) scalar PaginationAmount type Query { # メッセージ一覧を取得する messages( # 取得件数 first: PaginationAmount! # 指定した文字列が表すメッセージ以降を取得する after: String ): [Message!] } typealias PaginationAmount = Int // エイリアスでスキーマ上と型名を合わせると味がいい class QueryResolver : GraphQLQueryResolver { fun { // この処理が実行される時点で first が 100未満であることは保証される ... } } 独自のスカラー型を作成する方法は以下の2ステップです。 Coercing インタフェースを実装したクラスを作成する 作成した Coercing を元に GraphQLScalarType を作成し、Bean に登録する class PaginationAmountCoercing : Coercing<Int, Int { override fun parseLiteral(input: Any): Int? { // 入力チェックを失敗させる場合は CoercingParseLiteralException を throw する ... } ... } @Bean val PaginationAmount = GraphQLScalarType.newScalar() .name("PaginationAmount") .description("A positive integer with an upper bound") .coercing(PaginationAmountCoercing()) .build()!! 認証結果は GraphQLContext に保存しよう SpringBoot をベースにアプリケーションを作っていると認証結果のユーザ情報はリクエストスコープの Bean に保存するような形になりそうですが、 GraphQL には同一リクエストで使いまわすことができるコンテキストの仕組みが用意されています。 AuthContext という独自のクラスに User を持たせる例は以下のようになります。 GraphQLContext インタフェースを実装した AuthContext クラスを作成 build メソッドで AuthContext のインスタンスを返すような GraphQLContextBuilder を作成し Bean に登録 class AuthContext(val user: User?) : GraphQLContext { ... } @Bean fun authContextBuilder(): GraphQLContextBuilder = object : DefaultGraphQLContextBuilder() { override fun build( request: HttpServletRequest, response: HttpServletResponse ): GraphQLContext { // ユーザの情報を取得 val user = ... return AuthContext(user) } } AuthContext の生成はリクエストごとに1回実行されて、結果はリゾルバーで取得することができます。 class QueryResolver : GraphQLQueryResolver { fun messages( first: PaginationAmount, after: String?, environment: DataFetchingEnvironment // 引数に指定することで、ここからコンテキストの取得もできる { val() val user = authContext.user ... } } ユーザ情報のフィールドにするべきものとそうじゃないもの 認証済みユーザ専用の「おすすめコンテンツ」をスキーマで表現しようとすると、ユーザ情報の型におすすめコンテンツのフィールドを追加する形が考えられます。 type Query { # 現在のユーザ(未認証の場合は null) currentUser: User } # ユーザ情報 type User { # 会員の名前 name: String! ... # おすすめコンテンツ一覧 recommendedContents: [RecommendedContent] } ユーザ情報とおすすめコンテンツを取得するクエリは以下のようになります。 query { currentUser { name recommendedContents { ... } } } facebook が提供している GraphQL のサンプル*6と同じ設計方針となっていて一見自然な対応に見えますが、 今後の機能追加の方向によっては問題になってくる可能性があります。 例えば、未認証のユーザに対してもおすすめコンテンツを返さなければならなくなるかもしれません。 おすすめコンテンツ一覧を会員情報のフィールドとしていると、会員ではないユーザについてはそのフィールドにアクセスすることができなくなってしまいます。 このような場合は、会員情報とおすすめコンテンツのリレーションを断つのがシンプルです。 スキーマ定義の一部を修正したものは以下のようになります。 type Query { # 現在のユーザ currentUser: User # おすすめコンテンツ一覧 recommendedContents: [RecommendedContent] } ユーザ情報のフィールドにするものは ユーザを構成している要素である(e.g. メールアドレスなどの登録情報) ユーザの状態を表す要素である(e.g. 保有ポイント数) 他のユーザからも関連が見える必要がある(e.g. SNSの友達一覧) のいずれかの条件を満たすものにするのが良いでしょう。 認証が必要であることは Directive で表現しよう 未認証の場合に結果を返さないフィールド、もしくは型であることを示したいことがあります。 そのような時は Directive という機能を使えば宣言的に情報を付加することができます。 # 認証済みの場合のみアクセス可能 directive @auth on OBJECT | FIELD_DEFINITION type User @auth { name: String! } 実行時の振る舞いを変えるような Directive の実装方法は以下の2ステップです。 SchemaDirectiveWiring インタフェースを実装したクラスを作成する SchemaDirective として Bean に登録する 認証が必要なことを示す Directive の実装は以下のようになります。 class AuthDirective : SchemaDirectiveWiring { override fun): GraphQLFieldDefinition { val originalDataFetcher = environment.fieldDataFetcher val authDataFetcher = DataFetcher<Any { dataFetchingEnvironment val() if (authContext.user != null) { // 認証済みの場合。元のリゾルバーを呼び出す originalDataFetcher.get(dataFetchingEnvironment) } else { // 未認証の場合。 ... } } return environment.setFieldDataFetcher(authDataFetcher) } } @Bean fun = listOf( SchemaDirective("auth", AuthDirective()) ) エラーハンドリング graphql-java でのエラーハンドリングの方法はいくつかありますが、 GraphQLErrorHandler をカスタマイズする方法を紹介します。 デフォルトでは DefaultGraphQLErrorHandler が使われるようになっていて、リゾルバーからスローされた例外は "Internal Server Error(s) while executing query" というメッセージの1つのエラーに集約されてしまい詳細不明となってしまいますが、自由にカスタマイズすることが可能です。 実装方法は GraphQLErrorHandler インタフェースを実装したクラスを作成し、Bean に登録するのみです。 @Component class CustomGraphQLErrorHandler : GraphQLErrorHandler { override fun { // エラーハンドリングを実装する ... } } GraphQLErrorHandler をカスタマイズする以外の方法では、 SpringBoot の @ExceptionHandler アノテーションを使う方法*7 GraphQLError インタフェースを実装した例外をスローする方法 などがありますが、それらと比べると GrphQL の標準的なエラー表現である path や locations の情報がデフォルトで設定されている(他の方法では独自実装が必要) バリデーションエラーについてもカスタマイズ可能 エラーの数もカスタマイズ可能(レスポンスJSONの errors フィールドに任意の要素数で格納できる) などのメリットがあります。どこまでカスタマイズしたいか次第なところもありますが、おそらく一番自由度が高いカスタマイズ方法です。 フィールドで Nullable or Non-null を迷うようなら Nullable Non-null である必要がないフィールドを Non-null で定義してしまうと、取得できたはずのデータを返せなくなる可能性があります。 先ほども例に出したスキーマを例にして説明します。 # Schema type Query { # 現在のユーザ currentUser: User # おすすめコンテンツ一覧 recommendedContents: [RecommendedContent] } # Query query { currentUser { name } recommendedContents { title } } 上記のようなクエリを発行した際に何かしらエラーが発生し、おすすめコンテンツの情報が取得できず以下のような JSON を取得できたとします。 { "data": { "currentUser" : { "name": "エムスリー 太郎" }, "recommendedContents": null }, "errors": [ { "message": "failed to get recommended contents title", "path": ["recommendedContents"] } ] } この時、もし recommendedContents の型が [RecommendedContent]! のように Non-null だった場合、null になるはずだったフィールドの親のオブジェクトが null になります。つまりこの場合は data が null になり、取得できていたはずの currentUser のデータさえもクライアントに返らなくなります。 { "data": null, "errors": [ { "message": "failed to get recommended contents title", "path": ["recommendedContents"] } ] } (data フィールドは最上位のフィールドで Nullable です。) 上記のようなケースが考えられるため、 Nullable か Non-null か迷った時は Nullable とするのが良いと思われます。 また、複数のクエリが同時に問い合わせされた時のことを考えると、Query および Mutation 配下のフィールドは Nullable にしておくのが無難なのかもしれません。 Null可否についての考察はこちらの記事*8がとても参考になりました。 エラーとなった場合を例に出して少し詳しく見てみましたが、互換性の観点でも Nullable の方が望ましいです。 GraphQLをスマホアプリのAPIとして動かしつつスキーマ定義を変更することを考えます。その時、すでにリリースされているバージョンのアプリの互換性を保ちつつ変更する必要が出てきます。 サーバから null が返ってくるとクラッシュする可能性があるので危険! サーバが null を返さなくなっても問題ないので安全 フィールドの引数で Nullable or Non-null を迷うようなら Non-null 前のセクションではサーバからのレスポンスについては迷うようなら Nullable ということを述べましたが、 クライアントから送られる値については逆のことが言えます。つまり「Nullable or Non-null を迷うようなら Non-null」です。 互換性の観点で再び整理すると以下のようになるためです。 サーバが null を受け取れるようになっても問題ないので安全 サーバが null を受け取れなくなるとクエリ実行できない可能性があるので危険! 要素追加の可能性がある Enum を使うときは細心の注意を Enum の要素追加はサーバとクライアントで非互換になる可能性があります。 サーバ側は新しい Enum 要素を実装したバージョンをリリースすればいいですが、クライアント側(スマホアプリ)は、新しい Enum 要素を解釈できるバージョンのアプリをリリースし、ユーザの端末に新しいバージョンのアプリをダウンロードしてもらうところまでが必要になります。 Enum をクエリの結果として使う場合、要素追加される前のスキーマ定義を元にコードを生成した旧バージョンのアプリではサーバから返された新しい Enum 要素が解釈できないためです。 アプリの強制アップデート機能によって解消するという手段もありますが、エンジニアの都合でそれをやるのは避けたいです。 4つ目の要素が追加されようとしている Enum を例にして、いくつか解決策をあげます。 enum UserStatus { # 医師 DOCTOR # 医学生 MEDICAL_STUDENT # 薬剤師 PHARMACIST # 薬学生(これから追加される. 古いバージョンのアプリはこの値を知らない) # PHARMACY_STUDENT } 解決策1. unknown だった場合にどうするか決める Appoloクライアントの場合、未定義の Enum が返ってきたときにクラッシュさせないように unknown という状態にできます。 unknown なときにどうするか決めることができれば特に問題にはならないかもしれません。 解決策2. フィールドを変える 要素追加があるごとにフィールドを変えるという対策が取れます。 type User { # 薬学生を含まないステータス status: UserStatus! # 薬学生を含む新しいステータス(しかしフィールド名のネーミングはとても悪い...) newStatus: UserStatus! } フィールド名は拡張可能な形にしておく必要がありますが、命名はとても難しくなることが予想されます。 また、フィールドが増え続けるようなら、それはそれでアンチパターンにハマってしまっていると思われます。。 この方法を取る場合、サポートするクライアントのバージョンがわかっているようならコメント等で残しておくと良いでしょう。 そのバージョンの利用者がいなくなった時にフィールドを削除するのに使えます。 解決策3. Enum を使わない 上記の例であれば Enum にせずに同等の情報を返すフィールドを作る方法も取れます。 type User { # 学生かどうか isStudent: Boolean! # 薬学系ステータスかどうか isPharmacyStatus: Boolean! } 今後拡張の可能性が高いものは Enum として表現するよりも、それ以外のフィールドとして返してクライアント側で決定する方法の方が安全だと思われます。 先人の知恵を借りる 冒頭で述べました通り、GraphQL についてのナレッジがチームにはなかったため悩みどころは多かったです。 特にスキーマ設計についてはサーバサイド、クライアントサイドのエンジニアを交えて議論を重ねました。 スキーマ設計についての指針が欲しいと思っていたところで参考になったドキュメント・書籍を紹介します。 Relay Server Specification*9 Relay Server Specificationは GraphQL の拡張仕様です。スキーマ設計についていくつかの規約を定めています。 Relay に準拠した実装のライブラリも少なくないため、合わ��ておいて損はないでしょう。 GraphQL 公式サイト*10 GraphQL の一通りの機能についてドキュメントがあり、完全に理解した気分にさせてくれます。機能の説明となっているため使い所などわかりにくいところもありますが、やはり公式ドキュメントは読むべきです。 GraphQL スキーマ設計ガイド*11 あまり日本語化されていない GraphQL の設計周りについて書いてあります。 この書籍が配布された頃にちょうど悩んでいるところだったエラーハンドリングについて特に参考にさせていただきました。 We are hiring 今回は新規アプリのBFFにまつわる話をさせていただきました。 マルチデバイスチームではリリースされたばかりのアプリを成長させるべく一緒に開発に参加してくれる仲間を募集中です。 もちろんサーバサイドに限らず iOS / Android アプリのエンジニアも募集しています。 お気軽にお問い合わせください。 jobs.m3.com *1:初めてのGraphQL, Eve Porcello Alex Banks 著, 尾崎 沙耶 あんどうやすし 訳 *2:https://github.com/graphql-java/graphql-java *3:https://github.com/graphql-java-kickstart/graphql-java-servlet *4:https://github.com/graphql-java-kickstart/graphql-java-tools *5:https://github.com/graphql-java-kickstart/graphql-spring-boot *6:https://github.com/relayjs/relay-examples/tree/master/todo *7:graphql-spring-boot-starterのExceptionハンドリングがめっちゃ便利になってた https://shiraji.hatenablog.com/entry/2019/04/24/080000 *8:When To Use GraphQL Non-Null Fields https://medium.com/@calebmer/when-to-use-graphql-non-null-fields-4059337f6fc8 *9:Relay Server Specification https://relay.dev/docs/en/graphql-server-specification.html *10:https://graphql.org/ *11:GraphQLスキーマ設計ガイド https://github.com/vvakame/graphql-schema-guide
0 notes
craigbrownphd-blog-blog · 6 years ago
Text
GraphQL Java Example for Beginners [Spring Boot]
#ICYDK: Chicks like GraphQL Java Examples with Spring Boot too! GraphQL is a query language for APIs that allows clients to request limited data they need, making it possible for clients to gather data in a limited number of requests. GraphQL is a strongly-typed protocol and all data operations are validated against a GraphQL schema. In this article, we will look at a GraphQL Java example and build a simple GraphQL server with Spring Boot. http://bit.ly/2LqgHn3
0 notes
codeonedigest · 2 years ago
Text
Rest API Vs Graphql Tutorial with Example for Microservice Developers
Full Video Link - https://youtube.com/shorts/nFoO6xbEi4U Hi, a new #video on difference between #graphql & #restfulapi #restapi for #microservice #api #developers is published on #codeonedigest #youtube channel. @java #java #awscloud @awscloud
The core difference between GraphQL and REST APIs is that GraphQL is a specification, a query language, while REST is an architectural concept for network-based software. GraphQL is great for being strongly typed, and self-documenting based on schema types and descriptions and integrates with code generator tools to reduce development time. A REST API is an “architectural concept” for…
Tumblr media
View On WordPress
0 notes
codeonedigest · 2 years ago
Text
GraphQL Client Side & Server-Side Components Explained with Examples for API Developers
Full Video Link - https://youtube.com/shorts/nezkbeJlAIk Hi, a new #video on #graphql #mutation published on #codeonedigest #youtube channel. @java @awscloud @AWSCloudIndia @YouTube #youtube @codeonedigest #graphql #graphqlresolver #graphqltutorial
 Let’s understand the GraphQL components and the way they communicate with each other. The entire application components can be categories in to server side and client-side components. Server-side Components – GraphQL server forms the core component on the server side and allows to parse the queries coming from GraphQL client applications. Apollo Server is most commonly used implementation of…
Tumblr media
View On WordPress
0 notes
codeonedigest · 2 years ago
Video
youtube
Spring Boot GraphQL Mongo DB Project Tutorial with Example for API Devel... Full Video Link        https://youtu.be/JElcKeh9a5A Hello friends, new #video on #springboot #graphql #mongodb #api #microservices #application #tutorial for #developer #programmers with #examples are published on #codeonedigest #youtube channel.  @java #java #aws #awscloud @awscloud @AWSCloudIndia #salesforce #Cloud #CloudComputing @YouTube #youtube #azure #msazure #codeonedigest @codeonedigest   #graphqlspringboot #graphqlspringboottutorial #graphqlspringbootmicroservicesexample #graphqlspringbootexample #graphqlmongodbexample #graphqlmongodbspringboot #springbootmongodb #springbootgraphql #springbootgraphqltutorial #springbootgraphqlexample #springbootgraphqlresolver #springbootgraphqlschema #springbootgraphqlschemamapping #springbootgraphqlmongodb #mongodbtutorialforbeginners #springboottutorial #springbootproject #graphql
1 note · View note
codeonedigest · 2 years ago
Video
youtube
Spring Boot GraphQL API Project Tutorial with Example for Microservice D... Full Video Link        https://youtu.be/9vGNRyNAUooHello friends, new #video on #springboot #graphql #api #microservice #application #tutorial for #developer #programmers with #examples are published on #codeonedigest #youtube channel.  @java #java #aws #awscloud @awscloud @AWSCloudIndia #salesforce #Cloud #CloudComputing @YouTube #youtube #azure #msazure #codeonedigest @codeonedigest   #spring #springboot  #springboot  #springboot #springframework #springboottutorial #springbootfullcourse #springboottutorialforbeginners #springbootgraphqltutorial #springbootgraphql #springbootgraphqlexample #springbootgraphqlsubscription #springbootgraphqlapi #springbootgraphqlapplicationproperties #springbootgraphqlresolver #springbootgraphqlexamplegithub #springbootgraphqlmicroservicesexample #springbootgraphqlproject #graphqlspringboot #graphqltutorial #api
1 note · View note
craigbrownphd-blog-blog · 6 years ago
Text
GraphQL Java Example for Beginners [Spring Boot]
#ICYMI: Chicks like GraphQL Java Examples with Spring Boot too! GraphQL is a query language for APIs that allows clients to request limited data they need, making it possible for clients to gather data in a limited number of requests. GraphQL is a strongly-typed protocol and all data operations are validated against a GraphQL schema. In this article, we will look at a GraphQL Java example and build a simple GraphQL server with Spring Boot. http://bit.ly/2MXGYvd
0 notes
craigbrownphd-blog-blog · 6 years ago
Text
A Beginner’s Guide to GraphQL With Angular and Apollo
Let's build some connections. GraphQL has been gaining popularity lately, to the point where it has made its way to the forefront of API development. There are several GraphQL clients available today for front-end frameworks. The Apollo client is one of the more popular ones for Angular applications. In this article, we are going to build a small app using Angular and the Apollo client. In my last article, I talked about creating a GraphQL server with Spring Boot. We will use the same example for our Angular application. http://bit.ly/2MQx8uU
0 notes
craigbrownphd-blog-blog · 6 years ago
Text
GraphQL Java Example for Beginners [Spring Boot]
Chicks like GraphQL Java Examples with Spring Boot too! GraphQL is a query language for APIs that allows clients to request limited data they need, making it possible for clients to gather data in a limited number of requests. GraphQL is a strongly-typed protocol and all data operations are validated against a GraphQL schema. In this article, we will look at a GraphQL Java example and build a simple GraphQL server with Spring Boot. http://bit.ly/2NISWZ8
0 notes