Hands-On Swift 5 Microservices Development
eBook - ePub

Hands-On Swift 5 Microservices Development

Build microservices for mobile and web applications using Swift 5 and Vapor 4

  1. 392 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Hands-On Swift 5 Microservices Development

Build microservices for mobile and web applications using Swift 5 and Vapor 4

About this book

Learn to design and deploy fully functioning microservices for your applications from scratch using Swift, Docker, and AWS

Key Features

  • Understand server-side Swift development concepts for building your first microservice
  • Build microservices using Vapor 4 and deploy them to the cloud using Docker
  • Learn effective techniques for enhancing maintainability and stability of your Swift applications

Book Description

The capabilities of the Swift programming language are extended to server-side development using popular frameworks such as Vapor. This enables Swift programmers to implement the microservices approach to design scalable and easy-to-maintain architecture for iOS, macOS, iPadOS, and watchOS applications.

This book is a complete guide to building microservices for iOS applications. You'll start by examining Swift and Vapor as backend technologies and compare them to their alternatives. The book then covers the concept of microservices to help you get started with developing your first microservice. Throughout this book, you'll work on a case study of writing an e-commerce backend as a microservice application. You'll understand each microservice as it is broken down into details and written out as code throughout the book. You'll also become familiar with various aspects of server-side development such as scalability, database options, and information flow for microservices that are unwrapped in the process. As you advance, you'll get to grips with microservices testing and see how it is different from testing a monolith application. Along the way, you'll explore tools such as Docker, Postman, and Amazon Web Services.

By the end of the book, you'll be able to build a ready-to-deploy application that can be used as a base for future applications.

What you will learn

  • Grasp server-side Swift development concepts using practical examples
  • Understand the microservices approach and why Swift is a great choice for building microservices
  • Design and structure mobile and web applications using microservices architecture
  • Discover the available database options and understand which one to choose
  • Scale and monitor your microservices
  • Use Postman to automate testing for your microservices API

Who this book is for

The book is for iOS, iPadOS, and macOS developers and Swift programmers who want to understand how Swift can be used for building microservices. The book assumes familiarity with Swift programming and the fundamentals of the web, including how APIs work.

Frequently asked questions

Yes, you can cancel anytime from the Subscription tab in your account settings on the Perlego website. Your subscription will stay active until the end of your current billing period. Learn how to cancel your subscription.
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
Perlego offers two plans: Essential and Complete
  • Essential is ideal for learners and professionals who enjoy exploring a wide range of subjects. Access the Essential Library with 800,000+ trusted titles and best-sellers across business, personal growth, and the humanities. Includes unlimited reading time and Standard Read Aloud voice.
  • Complete: Perfect for advanced learners and researchers needing full, unrestricted access. Unlock 1.4M+ books across hundreds of subjects, including academic and specialized titles. The Complete Plan also includes advanced features like Premium Read Aloud and Research Assistant.
Both plans are available with monthly, semester, or annual billing cycles.
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Yes! You can use the Perlego app on both iOS or Android devices to read anytime, anywhere — even offline. Perfect for commutes or when you’re on the go.
Please note we cannot support devices running on iOS 13 and Android 7 or earlier. Learn more about using the app.
Yes, you can access Hands-On Swift 5 Microservices Development by Ralph Kuepper in PDF and/or ePUB format, as well as other popular books in Computer Science & Bioinformatics. We have over one million books available in our catalogue for you to explore.

Information

Writing the User Service

:Okay—let's start building the first service for our shop application! Everything should be set up at this point for you to start writing the services. What you learn in this chapter will equip you to build microservices within a bigger context. You will learn, step-by-step, what the code of a microservice looks like and how to interact with Vapor.
So far, we have been building up to this moment. You have learned the theory of how to build microservices and have prepared everything to get started. After you finish this chapter, you will be able to run your own, fully functional user manager service! It's the first microservice out of our example project and gives you a good idea of how to write your own user services. User services are very common across apps and websites, and the material of this chapter will hopefully help you with those as they come your way.
We are going to cover the following topics in this chapter:
  • Setting up and taking the first step
  • Exploring routes
  • Exploring models
  • Logging in and registering
  • Managing users
  • Understanding address management
  • Starting the service
Let's get started!

Technical requirements

For this chapter, you will need the following software components up and running:
  • Vapor Toolbox
  • Swift 5
  • Xcode 11+
  • macOS or Linux
We will assume you are using macOS, but all this should work the same under Linux.
You can find all the code for this chapter at the following GitHub repository: https://github.com/PacktPublishing/Hands-On-Swift-5-Microservices-Development/tree/master/Chapter 7/UserService

Setting up and taking the first step

In this section, we will set up our environment. Everything that we need in terms of code and software will be prepared here.
For you to start writing this service, you will need to have the following pieces in place:
  • A blank folder for this service
  • A new Git repository available
  • The microservice template we worked on in the previous chapters
If you have not completed any of the previous steps to have all three elements ready, please go back and finish those first. Microservices can be complex, and if not organized well, will end up in a mess.
This section will cover the following:
  • Setting up the template
  • Installing SendGrid
  • Setting up JSON Web Tokens (JWT) and utility functions
  • Setting up the database

Setting up the template

Let's start by setting up the template we created in the previous chapter. We don't need to rewrite what we have created before, and will simply use it as a basis for this service. We will now take the template we created and copy it into our current project folder. Then, we will modify it to fit our needs, which is to install SendGrid. Go through the following steps to do that:
  1. Go into the folder for the user manager, as follows:
$ cd ~/Shop\ Backend/UserService
  1. Now, copy the template from the original folder into our new folder, like this:
$ cp -r ../template/. . && rm -rf .build
  1. Now, open up the Package.swift file by using the following command:
$ open Package.swift
  1. Change the name attribute in the Package.swift file to UserService.
Now that we have set up the template, we can customize it by adding a few packages and dependencies.

Installing SendGrid

It is common for users to verify their emails when signing up. We want our service to include this functionality. Configuring our own Simple Mail Transfer Protocol (SMTP) mail server for this is a complex task and would require us to comply with a lot of common rules for sending mail. It is easier to use a service that already does that so that we do not have to worry about it. Services of this kind include Simple Email Service (SES) from Amazon Web Services (AWS), Gmail, Yahoo, and SendGrid. Since we want to customize the sender, we will use SendGrid, which offers a free plan for small projects. There is also a nice Vapor package we can use: https://github.com/vapor-community/sendgrid-provider.
To set up SendGrid, do the following:
  1. Go to https://sendgrid.com/ and create an account. Their free tier has plenty of room for us.
  2. Install the Vapor package by adding the following line to your Package.swift file:
.package(url: "https://github.com/skelpo/sendgrid-provider.git", from: "4.0.0")
  1. Add SendGrid to your .target function.
  2. Add the following lines to your Configuration.swift file within the configure function:
guard let sendgridApiKey = Environment.get("SENDGRID_API_KEY")
else {
fatalError("No value was found at the given public key
environment 'SENDGRID_API_KEY'")
}
let sendgridClient = SendGridClient(client: app.client, apiKey: sendgridApiKey)
This code is adding an environment variable that provides the API key for SendGrid to the module.
  1. Change the try routes(app) line to the following:
try routes(app, sendgridClient)
  1. Open Routes.swift and change the file lines, like this:
import Vapor
import SendGrid

func routes(_ app: Application, _ sendgridClient: SendGridClient) throws {
After installing SendGrid, we need to set up a JWT and utility functions next.

Setting up a JWT and utility functions

Our template already contains all we need to set up a JWT properly. For our backend, we now need to create the actual keys for signing and verification. To do this, follow these steps:
  1. Go to https://mkjwk.org/ and create a new key pair for our backend. Select 2048 as Key Size, Signing as Key Use, RS256 as Algorithm, and backend as the Key ID.
  2. Press Generate.
The result should look like this:

  1. Store the content under Keypair set in a file within your Shop Backend folder and call it keypair.jwks. DO NOT PUBLISH THIS FILE.
Generating keys can be done differently. This is simply an easy way to get started. Once you go into production, you should regenerate your keys using command-line tools, as mentioned on mkjwk.org.
  1. Create an .env file in the Shop Backend/UserService folder and write the following in it (you can add the .env file to your .gitignore file as well):
JWKS=<COPY_THE_KEYPAIR_AS_ONE_LINE_HERE>
And this is all we have to do. The SimpleJWTMiddleware has taken care of the rest for us.
Let's take a look at the actual middleware. Open the SimpleJWTMiddleware.swift file from https://github.com/proggeramlug/SimpleJWTMiddleware/blob/master/Sources/SimpleJWTMiddleware/SimpleJWTMiddleware.swift and you should see the following:
import Vapor import JWT public final class SimpleJWTMiddleware: Middleware { public init() { } public func respond(to request: Request, chainingTo next: Responder) ->
EventLoopFuture<Response> { guard let token = request.headers.bearerAuthorization?.token.utf8
else { ret...

Table of contents

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. About Packt
  5. Foreword
  6. Contributors
  7. Preface
  8. Introduction to Microservices
  9. Understanding Server-Side Swift
  10. Getting Started with the Vapor Framework
  11. Planning an Online Store Application
  12. Creating Your First Microservice
  13. Application Structure and Database Design
  14. Writing the User Service
  15. Testing Microservices
  16. Product Management Service
  17. Understanding Microservices Communication
  18. Order Management Service
  19. Best Practices
  20. Hosting Microservices
  21. Docker and the Cloud
  22. Deploying Microservices in the Cloud
  23. Scaling and Monitoring Microservices
  24. Assessment Answers
  25. Other Books You May Enjoy