How to Build an API using Strapi

Ever needed to build and ship an API in very little time? Read this article to learn how to use Strapi to get the job done.

APIs are so useful and ubiquitous in any application, and as a developer, you may be fazed by building an API in very little …


This content originally appeared on DEV Community and was authored by Uchechukwu Azubuko

Ever needed to build and ship an API in very little time? Read this article to learn how to use Strapi to get the job done.

APIs are so useful and ubiquitous in any application, and as a developer, you may be fazed by building an API in very little time. In this article, I will show you how to build a Node.js API so fast (perhaps, in 10 minutes) using the help of Strapi’s intuitive interface.

What You’ll Learn

  • How to build an API quickly with Strapi.
  • How to build a Node backend without writing Node code.
  • How to manage relational fields with Strapi.
  • How to add GraphQL endpoints to fetch and mutate your API.

This Article Is Written For

  • Developers that need to build backend APIs quickly.
  • Developers that want to build a backend, but only want to focus on the frontend.
  • Developers that want to build a Node backend API, but don’t have the Node expertise.

What You Will Build

In this article, you will start from scratch (i.e., from an empty directory), then you will go through all the steps needed to build an API using Strapi. The API that you will build will allow clients to make requests to manipulate content. The content, in this case, will represent blog posts (as in, for a blogging website - if you’d like to build out the frontend, moving forward.)

Prerequisites

What you’ll need for this tutorial:

  1. Knowledge of API; it might make sense to learn about it first.

  2. Node & NPM - You’ll need to have Node and NPM installed on your local machine. To confirm they’re installed, run the following commands in your terminal:

node -v && npm --v

The Node Package Manager comes installed with Node. If you don’t have them installed, you can follow the instructions on the official Node.js website.

This tutorial was completed using Node v14.18.1.

  1. Yarn - Yarn is a package manager that would help us manage our application dependencies in a way that is several times faster and more reliable than NPM. You can install yarn using:
npm install --global yarn

Table of Contents

Here’s what we’ll cover today:

👋 Intro to Strapi
⚙️ Setting up the Strapi project
🏗️ Building the Strapi backend
🤝 Understanding and using relations in Strapi
⚡ Delivering faster with GraphQL and Strapi
🤔 Conclusion

Intro to Strapi

Strapi is an open-source headless CMS (Content Management System) based on Node.js that gives developers the ability to easily build self-hosted, customizable, and performant content APIs (RESTful and GraphQL). With Strapi, weeks of API development can be saved, because it’s no-code, and building a robust API could be done in less than 20 minutes.

Isn’t that awesome? I thought so too. Let’s dive right into how that can be made possible.

Setting up the Strapi project

There are various ways to install a new Strapi project. However, the Strapi CLI is the best way to get started.

For starters, open a terminal and navigate to the directory where you’d like to create this project. Run the following command in your terminal to scaffold a new Strapi project:

yarn create strapi-app my-project --quickstart

Using the --quickstart flag at the end of the command provides you with the SQLite database by default, and directly creates the project in quickstart mode. If you’d like to switch databases, read more.

When project creation is completed, the app should automatically start at localhost:1337 on your browser.

If your app didn’t automatically start, run the following command in the project folder:

yarn develop

Open up the app folder with your IDE, and the project structure should look like mine below:

Building the Strapi backend

With the project folder now created, the first step to building a Strapi backend is to register an admin.

You can register an admin by filling the form that was provided on startup, as I have done below:

Then, click on the “LET’S START” button. This will create your account and take you to the Strapi admin UI, which you will use for development configurations.

Isn’t it amazing how you moved from yarn create to having a dashboard where you can create your very own API pretty soon?

At this point, you are ready to use the awesome powers of Strapi in building an API for blog posts. Let’s proceed.

Designing the Data Structure

At this point, we are going to start creating the data structure for our API. We can do this by creating content-types. The first content type we will build is for posts.

Go to the Content-Types Builder section and click on Create new collection type. A modal will appear, where you will enter post as the display name.

The Content-Types Builder allows to create and update content-types: single and collection types. Read more.

Then, a modal will appear which you will use to create the fields for the post content-type.

Hmm, what fields does a blog post always have… Let’s create the following ones:

  • title with type Text (required)
  • content with type Rich Text (required)
  • image with type Media (Single image) and (required)
  • author with type Text (required)

Now, you have a post content-type with 4 fields - Text, Rich Text, Media, and Text.

Hit Finish, then Save! Here you go, your first content-type has been created, and you have successfully created the schema for a blog post.

Schemas help to implement the database’s design. Database schemas are the blueprints that help developers visualize how databases should be built. They provide a reference point that indicates what fields of information the project contains.

Now, on the sidebar, we will see the “COLLECTION TYPES” section and if you go to the post section, you’ll find there are currently no posts.

You can create a brand new post by clicking Add new posts.

You’ll see that you are provided with a CMS for inputting data. Go ahead and fill up the fields (title, featured image, author, content) with information about the first post you’d like to add to your database. You can add lots of posts if you’d like.

Then hit Save, and Publish. A screenshot of mine is shown below:

To view the posts API, visit localhost:1337/posts. P.s.: Notice it pluralized the name of the collection type that we had set initially - post.

You will get a status 403 - forbidden error, as shown below:

That’s because we attempted to view the API as an unauthenticated user, and by default, viewing an API requires authentication. To make posts public, we have to grant read-access to the post content-type. To do this, head to the dashboard and under the “GENERAL” section.

  • Click on the Settings then Roles & Permission and click on the public role.
  • Check the article find and findone options under permission and save.

With these, you have permitted a public user to get all posts **GET** /posts, and also get a single post **GET** /posts/:id; something so similar to the REST API GET method.

Then hit Save!

Now, if we head over to localhost:1337/posts you should now see all your posts from the post endpoint this time.

You can access created endpoints with REST API methods, because by default, Strapi provides our endpoints via REST, but later in this article, I will show you how endpoints can be accessed via GraphQL

In the project folder, the ./api/**/config/routes.json files define all available endpoints for the clients. By default, Strapi generates endpoints for all your Content Types. Read more.

Looks like we’re making progress. Doesn’t it?

Now we have created a post, the content is stored in your database so that you can have access to your data when you need to.

If you look through the posts endpoint, you’d notice that one other benefit of Strapi is that it supports image optimization too. You are given the ability to render different image formats including thumbnail, large, medium, and small.

With Strapi, you also don’t have to go through the stress of building out an MVC project structure - creating a database, database connections, models, etc. Here, it’s all done under the hood for you. We’ll have a look at that pretty soon.

Isn’t it beautiful to see that we are making headway?

Back in your IDE, you will now see that a ./api/posts/ folder has been created in the project folder, which is a reflection of the posts endpoint you created on the admin panel.

In the models folder, the posts.settings.json file defines the post schema that you created, as shown below:

As your app grows -- the more content-types(endpoints) you add up, the more folders are created in the api directory.

Also, note that image uploads are stored in the public/uploads folder.

I feel it makes huge sense that all of your code corresponds to all actions made on the dashboard. What do you think?

Understanding and using relations in Strapi

Let’s say you have a collection of videos, and for each blog post; a video should be embedded within. To establish a connection between a video from the videos collection and its associated blog post, you first have to learn how to use relations in Strapi.

Relation-type fields added to a content-type from the Content-Types Builder allow to establish a relation with another content-type - mandatorily a collection type. These fields are called "relational fields".

With our new-found knowledge, let’s go ahead and create the video collection - to demonstrate how to set up relations in Strapi.

Go to the Content-Types Builder section and click on Create new collection type. Enter video as the display name.

Then add the following field for the video content-type:

  • url with type Text (required)

Hit Finish, then Save! Now, your second content-type has been created, and you have successfully created the schema for a video.

To continue, grab a video URL, perhaps the one for your favorite YouTube video.

Because we want to create a link between the post collection and the video collection, we also need to add a new field called video in the Posts collection. The field type for this would be Relation, and we can choose the kind of relationship we want between posts and videos (by selecting any of the 6 options), to keep things simple in this demonstration, we’ll choose the one to one relationship where a post has a video, as shown below:

Note: For a field to be a relation, it has to be a collection type.

Hit the Finish button when you’re done.

Now your post schema should look like this:

With these, the video field in the Posts collection has a relation with the Videos collection.

To continue, navigate to the Videos sections under the “COLLECTION TYPES” in your dashboard, then click the Add New Video button to add a video to your Videos collection as shown below:

Hit Save, then Publish.

With the video added, we can now link it with a blog post, by heading to the post of choice in the Posts collection, clicking the Edit button, and selecting the video URL you’d like to add to that post.

Tadaa! If you visit localhost:1337/posts on your browser, you will see that the posts endpoint has been updated and the video has been added to the post where you included it, as shown below:

Delivering faster with GraphQL and Strapi

Delivering applications faster is always a top priority. In this section, you will learn how to easily query your data through a generated GraphQL schema.

To get started with GraphQL in your app, you first have to install the plugin by running the following command in your project directory:

yarn strapi install graphql

With the GraphQL plugin installed, you will be able to add a GraphQL endpoint to fetch and mutate your content.

Restart the app using:

yarn develop

When you visit localhost:1337/graphql in your browser, you should see the interface (GraphQL Playground) that will help you to write a GraphQL query to explore your data

If you’d like to access the id, title, url of the featured image, author, and url of the video for blog posts, you can write the query as I’ve shown below:

Image description

We were able to grab data pretty fast and conveniently! Also, using the sidebar, you can have a peek at your schema. Awesome!

Conclusion

In this article, you learned how fast, easy to use, and powerful Strapi is for building APIs. Setting up our backend was super seamless. Just create your collections and Strapi generates RESTful endpoints by default, or if you’d prefer to use GraphQL endpoints, simply install the plugin. All of these, using best web practices. Awesome stuff, indeed!

If you have any questions or suggestions, feel free to post a comment, email, or DM me.

If you enjoyed this article, please hit the LOVE ❤️ button as many times as you wish. Thanks!!!

Resources

Strapi developer documentation


This content originally appeared on DEV Community and was authored by Uchechukwu Azubuko


Print Share Comment Cite Upload Translate Updates
APA

Uchechukwu Azubuko | Sciencx (2021-12-07T18:06:34+00:00) How to Build an API using Strapi. Retrieved from https://www.scien.cx/2021/12/07/how-to-build-an-api-using-strapi/

MLA
" » How to Build an API using Strapi." Uchechukwu Azubuko | Sciencx - Tuesday December 7, 2021, https://www.scien.cx/2021/12/07/how-to-build-an-api-using-strapi/
HARVARD
Uchechukwu Azubuko | Sciencx Tuesday December 7, 2021 » How to Build an API using Strapi., viewed ,<https://www.scien.cx/2021/12/07/how-to-build-an-api-using-strapi/>
VANCOUVER
Uchechukwu Azubuko | Sciencx - » How to Build an API using Strapi. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/12/07/how-to-build-an-api-using-strapi/
CHICAGO
" » How to Build an API using Strapi." Uchechukwu Azubuko | Sciencx - Accessed . https://www.scien.cx/2021/12/07/how-to-build-an-api-using-strapi/
IEEE
" » How to Build an API using Strapi." Uchechukwu Azubuko | Sciencx [Online]. Available: https://www.scien.cx/2021/12/07/how-to-build-an-api-using-strapi/. [Accessed: ]
rf:citation
» How to Build an API using Strapi | Uchechukwu Azubuko | Sciencx | https://www.scien.cx/2021/12/07/how-to-build-an-api-using-strapi/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.