Designing Web APIs with Strapi - Khalid Elshafie - E-Book

Designing Web APIs with Strapi E-Book

Khalid Elshafie

0,0
22,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Strapi is a Node.js-based, flexible, open-source headless CMS with an integrated admin panel that anyone can use and helps save API development time. APIs built with Strapi can be consumed using REST or GraphQL from any client. With this book, you'll take a hands-on approach to exploring the capabilities of the Strapi platform and creating a custom API from scratch.
This book will help JavaScript developers to put their knowledge to work by guiding them through building powerful backend APIs. You'll see how to effortlessly create content structures that can be customized according to your needs, and gain insights into how to write, edit, and manage your content seamlessly with Strapi. As you progress through the chapters, you'll discover a wide range of Strapi features, as well as understand how to add complex features to the API such as user authentication, data sorting, and pagination. You'll not only learn how to find and use existing plugins from the open-source community but also build your own plugins with custom functionality with the Strapi plugin API and add them to the admin panel. Finally, you'll learn how to deploy the API to Heroku and AWS.
By the end of this book, you'll be able to build powerful, scalable, and secure APIs using Strapi.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 254

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Designing Web APIs with Strapi

Get started with the Strapi headless CMS by building a complete learning management system API

Khalid Elshafie

Mozafar Haider

BIRMINGHAM—MUMBAI

Designing Web APIs with Strapi

Copyright © 2022 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Pavan Ramchandani

Publishing Product Manager: Aaron Tanna

Senior Editor: Keagan Carneiro

Content Development Editor: Adrija Mitra

Technical Editor: Shubham Sharma

Copy Editor: Safis Editing

Project Coordinator: Rashika Ba

Proofreader: Safis Editing

Indexer: Manju Arasan

Production Designer: Joshua Misquitta

Marketing Coordinator: Anamika Singh

First published: February 2022

Production reference: 1210122

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

978-1-80056-063-5

www.packt.com

To Ihsan, Elshafie, Bushra, Azza, Zhang He, and Sami for always loving and supporting me. To Hadi, without whom this book would have been completed way earlier. To myself, well done.

– Khalid Elshafie

To Meriem, for her patience and support before, during, and after writing the book. To Hayat and Hayder, my beautiful parents, for getting us here against all odds.

To Sudan and its youth, bravely forging a brighter future for all of us.

– Mozafar Haider

Contributors

About the authors

Khalid Elshafie is an experienced, senior full stack developer/software engineer with over 10 years of experience working across multiple frontend and backend technologies involved in designing and developing scalable web and mobile applications using multiple technologies, as well as in a variety of workplaces, from start-ups to larger consultancies. Khalid's passion for software engineering extends to the creation of barmaga.io, with Mozafar, where he has 45+ hours of video content on JavaScript, React.js, AWS and Serverless, Node.js, and Strapi. He also has a well-established YouTube channel with content focused on teaching programming.

I wish to thank my loving wife and son for their continued support and encouragement throughout the long process of writing this book. Also, I would like to thank Mozafar for introducing me to the world of programming 20 years ago, and last but not least, special thanks to Rares Matei for his tremendous efforts in providing valuable technical feedback for this book.

Mozafar Haider is a senior full stack engineer with over 15 years of experience working in organizations ranging from early-stage start-ups to scale-ups and corporates, in Barcelona, London, and Glasgow, among other places. He's passionate about teaching coding, especially to groups under-represented in tech, and was one of the co-founders of a coding school for refugees based in Glasgow. He also created, along with Khalid, barmaga.io, a platform for teaching coding in Amharic, Arabic, and Swahili.

I would like to thank Khalid for getting me involved in this project in the first place. We've come a long way since trying to learn ASP.NET 20 years ago on a hot summer's day in Khartoum. And a special thank you for pushing through the final phases of the book when I became overwhelmed with other life events. Here's to another 20 years of exciting projects!

About the reviewer

Rares Matei works for Nrwl.io on NxCloud, a zero-config distributed computation caching solution, helping teams and clients to speed up and scale their development practices with an open source tool called Nx, while also advising clients on web development best practices. He enjoys learning by teaching and has devised Egghead.io courses on TypeScript, reactive programming, and GraphQL. He is an organizer of the GlasgowJS meetup and an occasional speaker at other meetups and conferences.

Table of Contents

Preface

Section 1: Understanding Strapi

Chapter 1: An Introduction to Strapi

What is Strapi?

Why use Strapi? (The benefits of Strapi)

Open-source Node.js

Database-agnostic

Customizable (extendable)

RESTful and GraphQL

Users and permissions

Preparing the development environment

Installing Node.js

Installing Visual Studio Code (optional)

Installing Yarn

Installing Docker (optional)

Installing Postman

Creating a Strapi application

Overview of the admin panel

Understanding server scripts

The develop script

The start script

The build script

The Strapi script

Summary

Chapter 2: Building Our First API

Exploring the project structure of a Strapi application

The commands to run Strapi

The project structure

Under the hood – the components that make up Strapi

Defining the API requirements

Creating our first content-type – a classroom

Using the Strapi CLI instead of the admin panel

Clarifying Strapi terminology

Content-types, resources, object types, and models

Interacting with the Strapi API

Setting permissions

What did we just create?

Understanding the makeup of a Strapi API

Routes, controllers, services, and models

Content-types in code

Summary

Chapter 3: Strapi Content-Types

What is the Content-Type Builder plugin?

Creating and managing content-types

Creating a title field

Creating a slug field

Creating a type field

Creating url and contents fields

Understanding relations in Strapi

One-way

One-to-one

One-to-many

Many-to-one

Many-to-many

Many-way

Creating a Tutorial and Classroom relation

Creating a tutorial from the admin panel

Interacting with the API endpoints from Postman

Differences between SINGLE TYPES and COMPONENTS

Creating components

Summary

Chapter 4: An Overview of the Strapi Admin Panel

Navigating around the admin panel

Content Manager

PLUGINS

GENERAL

Marketplace

Plugins

Settings

Managing admin users

The difference between Users and admin users

Creating new admin panel users

Managing admin panel roles

Managing content effectively

Searching and filtering to query our data

Customizing the table view

Customizing the details view

Using the Media Library

Media types in API responses

Summary

Section 2: Diving Deeper into Strapi

Chapter 5: Customizing Our API

The routes – where it all starts

The default routes

Disabling a core route

Adding a new route

Handling routes with controllers

Adding a new controller handler for our endpoint

Controllers – it's all about context

Reusing logic with Strapi services

Communicating with the database using the Entity Service API

Returning a unified response

Populating relationships

Sanitizing data – hiding passwords

Overriding the default CRUD APIs

Tweaking database queries and responses with life cycle hooks

Using hooks

DRYing the hook's logic with services

Summary

Chapter 6: Dealing with Content

Creating sample data

Cleaning up

Sorting API content

What about sorting on multiple fields?

Filtering API content

Paginating API content

Under the hood – how it works

Summary

Chapter 7: Authentication and Authorization in Strapi

Understanding the difference between admin users and API users

API login and sign-up

What if I want to change the JWT expiration time?

What if I want to change the JWT secret?

Securing API routes

Under the hood – how it works

Using Strapi roles and permissions

Creating the Student role

Creating the Teacher role

Creating the Admin role

What if I want to change the default role for a new user?

Working with policies

Creating a policy

Honorable mention – OAuth providers

Summary

Chapter 8: Using and Building Plugins

Exploring the Strapi plugin ecosystem

What is a plugin in Strapi?

Installing and using plugins from the Marketplace

Installing the API Documentation plugin from the CLI

Finding more plugins

Use case – Enabling GraphQL for our API

Use case – Sending an email from Strapi

Sending an email using the Email plugin

Plugins and providers

Hooking our API to send an email

Creating our own plugins

Plugin development – frontend versus development

Building our plugin

Updating the model

Building the Enrollments component

Creating an API token

Displaying enrollments in the plugin

Using Strapi Design System

Summary

Section 3: Running Strapi in Production

Chapter 9: Production-Ready Applications

Seeding the database

Keeping permissions in sync

Serving media from an S3 bucket

Using PostgreSQL

Testing PostgreSQL locally

Summary

Chapter 10: Deploying Strapi

Deploying to Heroku

Deploying to AWS Fargate

Step 1 – Creating a Docker image for our API

Step 2 – Creating a Docker repository on AWS ECR

Step 3 – Creating an AWS Fargate cluster

Troubleshooting

Cleaning up

Summary

Chapter 11: Testing the Strapi API

An overview of software testing

Configuring test tools

Setting up the test environment

Preparing the database configuration

Preparing the Strapi instance

Writing and running tests

Testing a public endpoint

Testing a secure endpoint

Summary

Appendix: Connecting a React App to Strapi

About the React app

Understanding the React app folder structure

Running the app

Other Books You May Enjoy

Section 1: Understanding Strapi

Each journey starts with a first step. Our first step will be to understand the concept of headless CMS (short for Content Management System) and why Strapi is one of the most popular headless CMS around. Then, the chapters will move onto how to prepare the development environment and install and set up Strapi to build our first API.

In this section, we will cover the following topics:

Chapter 1, An Introduction to StrapiChapter 2, Building Our First APIChapter 3, Strapi Content-TypesChapter 4, An Overview of the Strapi Admin Panel

Chapter 1: An Introduction to Strapi

This chapter gives an introduction to Strapi. First, we will explain what Strapi is and what are the benefits of using it in developing API (short for application programming interface). Then, we will see how to set up and prepare our development environment to work with Strapi. Afterward, we will create a simple API to help us get started with Strapi. Finally, we will have a quick look at the server scripts offered by Strapi to start and stop the development server.

These are the topics we will cover in this chapter:

What is Strapi?Why use Strapi? (The benefits of Strapi)Preparing the development environmentCreating a Strapi applicationUnderstanding server scripts

What is Strapi?

Strapi is a headless content management system (CMS).

A CMS is a software application used for web development that allows users to create, edit, and publish content.

A traditional CMS, such as WordPress, tightly couples the frontend and the backend—that is, the structure of the content and how it is presented. However, unlike traditional CMSes, a headless CMS is entirely decoupled from the presentation layer. The term headless comes from separating the head (the frontend) from the body (the backend). A headless CMS does not care about how the contents get displayed; instead, it provides a content-first approach with an API to access and display the data in any format desired.

You can see the differences between a traditional CMS and a headless CMS in the following diagram:

Figure 1.1: Traditional CMS versus headless CMS

"Strapi" is wordplay for Bootstrap API. As the name suggests, it aims to help developers build (bootstrap) an API quickly. Strapi saves API development time through an integrated easy-to-use admin panel and a solid set of core features out of the box. Whether you are a backend, full stack, or frontend developer, you will find it extremely easy to get started with Strapi and API development without reinventing the wheel and wasting time in building common features such as basic create, read, update, and delete (CRUD) operations or authentication and authorization.

Now that we have familiarized ourselves with Strapi, let's see some of the advantages of using it.

Why use Strapi? (The benefits of Strapi)

There are several advantages to using Strapi, and we will outline some of the major benefits and reasons for using it next.

Open-source Node.js

Strapi is open-source and built on top of a popular Node.js framework: Koa. Its code is accessible and easily extendible. It's supported by a thriving company but also by a large community of contributors. You can find Strapi's code on GitHub at https://github.com/strapi/strapi.

Database-agnostic

Strapi can work with different database systems. It can be set up and configured to work with PostgreSQL, MySQL, MongoDB, and SQLite. We will see in Chapter 9, Production-Ready Applications, how we can configure Strapi to work with PostgreSQL.

Customizable (extendable)

Strapi is highly configurable to suit each project's specific requirements. All of the data types are created from scratch through the admin panel. Additionally, the Strapi plugin system makes it easy to extend its functionality with features such as database documenting, image uploads, and email configuration. We will discuss the Strapi plugin system in a later chapter of this book.

RESTful and GraphQL

Strapi provides a REpresentational State Transfer (REST) API out of the box. The API can be consumed from any web client (React, Angular, Vue.js, and so on), mobile applications, or even internet of things (IoT) applications using REST or GraphQL via a plugin.

Users and permissions

Strapi comes with a users and permissions model out of the box that allows you to define which endpoint is available for which user/role. Additionally, you can use Open Authorization (OAuth) to enable authentication via third-party providers such as GitHub, Facebook, Twitter, Google, and many others.

Now that we have understood what Strapi is all about, let's see how we can prepare our development environment to start developing our API.

Preparing the development environment

Before we start developing our API, we will need to prepare our development environment first. Next, we will look at the components and packages that we will be needing throughout the book.

Note

You can install the packages in any order you want. Some of the packages here are not a must-have, but it's highly recommended to install them to avoid having any issues while following the examples in this book.

Installing Node.js

To install Node.js, head to the official website, https://nodejs.org, and download the long-term support (LTS) version that matches your operating system. At the time of writing this book, version 16.13.2 is the latest LTS version and the version recommended by Strapi, as illustrated in Figure 1.2. Only LTS versions are supported by Strapi, the other versions of Node.js are not guaranteed to be compatible.

Figure 1.2: Node.js LTS version

Once you have installed Node.js, open your favorite terminal and run the following command to verify the Node.js version:

node –v

You should see the version of the installed Node.js on the terminal.

Installing Visual Studio Code (optional)

Visual Studio Code (VS Code) is a feature-rich and powerful integrated development environment (IDE), and we will be using it as our default editor. You are free to use whichever editor you feel comfortable with. However, we highly recommend installing and using VS Code to follow along with the examples in this book.

To download and install VS Code, head to https://code.visualstudio.com and download and install the appropriate build for your operating system.

Installing Yarn

Yarn (https://yarnpkg.com) is a JavaScript package manager. We will be using it as our default package manager since it's the package manager used by Strapi itself.

To install Yarn, open your favorite terminal and execute the following command:

npm install -g yarn

Once the installation is complete, run the following command to verify that Yarn has been installed successfully:

yarn –v

The version of Yarn should be displayed in the terminal. At the time of writing this book, version 1.22 is the latest version.

Installing Docker (optional)

We will be using Docker to install and manage a Postgres database for our API in a later chapter of the book. Docker can help us easily work with different database systems such as Postgres, MySQL, or MongoDB. To install Docker, head to https://docker.com/get-started and download and install Docker Desktop for your operating system.

Once you have installed Docker, execute the following command in your terminal to verify the installation:

docker –version

The Docker version should be displayed in the terminal. At the time of writing this book, version 20.10 is the latest version.

Alternatively, you can install Postgres using a different method of your choice.

Installing Postman

Postman is a great API client, and we will use it to interact with our API. Head to the Postman website at https://www.postman.com/downloads/ and download the version matching your operating system.

Once we have the development environment set up, we can proceed with creating our API.

Creating a Strapi application

Begin by running the following command on your terminal:

yarn create strapi-app strapi-lms --quickstart

The preceding command will set up a project using the latest version of Strapi with the default settings. Using a SQLite database, start the server on port 1337 and launch the admin dashboard.

Note

If we remove the –-quickstart flag, we will enter manual setup mode, where we will be asked a few questions to configure Strapi.

If the admin panel did not launch automatically, you can open your browser and navigate to http://localhost:1337/admin.

The first time you log in to the admin dashboard, you will be presented with a form to create the first administrator user. Complete the form to create an administrator user and sign in to the admin panel.

Overview of the admin panel

We will discuss the admin panel in greater detail in Chapter 4, An Overview of the Strapi Admin Panel. However, for now, we will just give a quick overview of the admin panel layout.

The admin panel is easy to navigate. On the left-hand side, we have our main control sidebar. It can be divided into three main categories, as follows:

Figure 1.3: Strapi main sidebar

Content Manager

This is where the API content lives, and you can manage API content from this section. At the moment, there is only one model, Users. We will see more models here as we progress in developing the API.

Plugins

The PLUGINS section allows you to customize Strapi. There are two essential plugins available out of the box: the Content-Type Builder and Media Library plugins.

The Content-Types Builder plugin is the core of Strapi customization; we will use it to create new models in our API and create a relationship between those models. As this plugin is critical in developing the API, we have dedicated Chapter 3, Strapi Content-Types, to discussing it in greater detail.

The Media Library plugin, as the name suggests, is used to manage all API media files.

General

This section contains Strapi settings where you can use the Marketplace to install new plugins, configure plugin settings, and edit general settings such as adding additional administrator users.

The --quickstart flag will bootstrap the Strapi application and start the development server for us. While you are developing a Strapi application, you will want to start and stop the server yourself. Let's see in the next section how to work with Strapi scripts to manage the server.

Understanding server scripts

Strapi comes with a few scripts that can be used in managing the development server as well as starting the server in production. If you open the package.json file, you will see the following four scripts:

Figure 1.4: Strapi server scripts

The develop script

The develop script will start the server in development mode, with autoreload enabled. Basically, it will watch for any changes in the project files and restart the server if there are any. This script is intended for local development, and it should never be used in a production environment.

The start script

The start script will start the server with autoreload disabled. This script is intended to start the server in a production environment.

The build script

This script allows you to rebuild the admin panel. The Strapi admin panel is built using React.js, but in some situations, you might want to customize or extend the admin panel. In such cases, you will need to rebuild the admin panel again using the build script. The admin panel is built once when you have created a project and every time you install a plugin that requires changes to the admin panel.

The Strapi script

This script is an alias to the Strapi command-line interface (CLI), and we can use it to generate new content in our system. We will explore the Strapi CLI in the next chapter.

Summary

In this chapter, we started by explaining the concept of a headless CMS and saw how it is different from a traditional CMS. We then introduced Strapi, an open-source headless CMS, and listed the benefits of using Strapi in developing APIs.

Then, we started preparing the development environment and installed the requisite packages and software, as well as creating a sample application that we will be using throughout the rest of this book. Finally, we had a quick look at the different server scripts offered by Strapi.

In the next chapter, we will have a deeper look at the typical structure of a Strapi application. We will also build our first API in the system and learn how to use the Strapi Content-Types Builder plugin to define fields needed for the API.

Chapter 2: Building Our First API

In this chapter, we will create our first API endpoint. We will explore the structure of a Strapi API project, and what modules and files Strapi creates for us. We will touch on the concept of a content-type and explore the structure and commands of a typical Strapi application.

The topics we will cover in this chapter are as follows:

Exploring the project structure of a Strapi applicationDefining the requirements – what are we going to build?Creating our first content-type using the admin panel and the command-line interface (CLI)Clarifying Strapi terminology – content-type, resources, and object typesInteracting with our APIUnderstanding the makeup of an API – routes, controllers, services, and models

Exploring the project structure of a Strapi application

When we ran the strapi-app CLI tool with yarn create strapi-app, the command generated a new blank project for us. Let's spend some time exploring the structure of the project and the packages that were installed for us.

The commands to run Strapi

Out of the box, the package.json file includes four Strapi-related commands that provide aliases for the Strapi CLI:

Development mode: While developing, we will run the API using the yarn develop command. This is an alias for strapi develop, which runs the Strapi instance in development mode, enabling features such as auto-reload and writing files to the code base when we change options in the admin panel. It also builds the admin panel.Production mode: For running in production, we can use yarn start


Tausende von E-Books und Hörbücher

Ihre Zahl wächst ständig und Sie haben eine Fixpreisgarantie.