Strapi – GraphQL Unauthenticated CRUD operations
Hi there! Today I will continue to develop a recent project in Strapi, called id-card-repository. If you are new, please check the previous article here.
Specifically, the main topic is CRUD operations using GraphQL with Strapi. CRUD stands for Create, Read/Retrieve, Update, and Delete. CRUD operations are essential as data stored in databases dynamically change. To understand deeply about CRUD operations, you can read this. So, let’s dive in!
— Continuing development using Strapi —
First, open Command Line Interface (CLI) and change the directory to the id-card-repository folder by typing :
$ cd id-card-repository
Run Strapi application using yarn :
$ yarn develop
Note : If you use npm : $ npm run develop |
Next, type localhost:1337
in any browser’s address bar, then you will be redirected to the strapi login page. Fill in your username and password to login. Dashboard page is seen immediately if login is successful.
Good! Eventually we should create an entry in collection types : Id-card-repositories.
— CRUD —
According to spec.graphql.org, there are three types of operations that GraphQL models :
query
– a read‐only fetch.mutation
– a write followed by a fetch.subscription
– a long‐lived request that fetches data in response to source events.
CRUD operation : Create
First, I would like to do this operation using User Interface.
So, just click the Id-card-repositories tab on the left side of the page and click the +Add New id-card-repository button.
Fill in the fields we have created previously.
Some fields are not filled in, as it is set to nullable, or not required fields.
Do not forget to click the save button, if you finished filling in.
Voila! As you can see, we have created an entry successfully!
We have created an entry using the user interface provided by Strapi. Okay then, let us create a new record using GraphQL API !
mutation
is used to create, update, and delete an entry.
Below is an example :
- Initially, we have three entries.
- Using
mutation
, we can create an entry like this.
Query : mutation{ createIdCardRepository( input: { data: { kind: P, identifier: “PassportID” name: “James Maddison”, birthPlace: “Manchester, United Kingdom”, #birthDate: “1990-03-04”, gender: M, bloodType: A, address: “Red Road, Manchester”, religion: “Islam”, marriageStatus: S, occupation: “Footballer”, nationalityCode: “UK”, #expiryDate: “2025-05-05”, issuerCountryCode: “UK”, #issuedDate: “2020-05-05”, statusCode: D, #uploadedAt: “2020-06-05” } } ) { idCardRepository { kind identifier name birthPlace birthDate gender bloodType address religion marriageStatus occupation nationalityCode expiryDate issuerCountryCode issuedDate statusCode uploadedAt } }} |
- We have successfully created the fourth entry!
CRUD operation : Read/Retrieve
In the admin dashboard page, we can see, read, or retrieve data just by clicking the Id-card-repositories tab. However, we will conduct this operation using GraphQL.
A query operation is not mandatory when retrieving entries. Nonetheless, in Strapi documentation, you will see examples using query operations.
Before starting, open a new tab in your browser then type : localhost:1337/graphql
.This will guide you to GraphQL Playground.
Just delete the comment saying, “# Write your query or …”. Next, type braces { } and press ctrl+space buttons, to show suggestions given by GraphQL. Then choose idCardRepositories.
Again, press ctrl+space buttons, to show suggestions given by GraphQL. This time, we will input fields created. Just click the enter button if you want to select the suggestion given by GraphQL.
If we look into the response, there are some null fields. This happens because we did not give any value when creating this entry. This can be updated later.
Great ! Now if you want to retrieve a single entry, you need an id to specify the record. Below is an example :
On the other hand, id is not required to retrieve multiple records.
“ What if there are some sensitive fields that should not be shown in the API response? ”
We can configure this by setting the sensitive fields to Private Fields.
Just go to the Content-Types Builder tab on the left side of the page.
In this project, for instance, kind and identifier fields are considered as sensitive fields. So, click the kind tab then go to Advanced Settings. Here, we will give a mark to Private field.
Same thing goes for the identifier field.
If we return to the GraphQL Playground, both of the kind and identifier fields are not shown in the suggestion. This happens because of the Private field configuration, we have set above.
“We can just type manually, can’t we?”
Let’s give it a try then.
Boom! It is showing errors which are related to kind and identifier fields.
So, currently no field is checked as Private field.
“ What if I want to retrieve a specific single entry/datum? “
In this case, we will change idCardRepositories to idCardRepository. However, we need an id to specify the entry we want to retrieve. For instance :
“ May I end a field name with a comma(,) ? ”
In GraphQL documentation, they do not give any commas(,). However, it does not result in error if we give.
With commas(,)
Without commas(,)
In retrieving either a single datum or multiple data, you will use query operation. Nevertheless, you can fetch entries without the ‘query’ word.
Retrieve a single entry :
Query : query{ idCardRepository(id: “5eeaf28ed3017e117fba6e41”){ kind identifier name birthPlace birthDate gender bloodType address religion marriageStatus occupation nationalityCode expiryDate facePhoto{ _id createdAt updatedAt name alternativeText caption width height formats hash ext mime size url previewUrl provider provider_metadata } cardImage{ _id createdAt updatedAt name alternativeText caption width height formats hash ext mime size url previewUrl provider provider_metadata } personWithCardPhoto{ _id createdAt updatedAt name alternativeText caption width height formats hash ext mime size url previewUrl provider provider_metadata } issuerCountryCode issuedDate faceTop faceLeft faceWidth faceHeight statusCode uploadedAt }} |
Retrieve all entries :
Query : query{ idCardRepositories{ kind identifier name birthPlace birthDate gender bloodType address religion marriageStatus occupation nationalityCode expiryDate facePhoto{ _id createdAt updatedAt name alternativeText caption width height formats hash ext mime size url previewUrl provider provider_metadata } cardImage{ _id createdAt updatedAt name alternativeText caption width height formats hash ext mime size url previewUrl provider provider_metadata } personWithCardPhoto{ _id createdAt updatedAt name alternativeText caption width height formats hash ext mime size url previewUrl provider provider_metadata } issuerCountryCode issuedDate faceTop faceLeft faceWidth faceHeight statusCode uploadedAt }} |
If you need to fetch specific records, for instance, a community member whose name is Michael, you can add filters stated in the documentation.
Below is an example to retrieve only a single entry, even though you have more than one record.
CRUD operation : Update
A mutation
operation is required again. Basically, updating a record using GraphQL API is quite similar to SQL, as where exists in GraphQL as well.
For example, you are considering updating James’ record (fourth entry) as he has moved recently and has just married his crush. The fields you are going to update are address and marriageStatus.
This is James’ address and marriage status (before) :
Let us modify this to keep data updated !
Some points to consider when updating a record :
- When creating a record, you use createIdCardRepository. Just like that, updating an entry forces you to include updateIdCardRepository instead of createIdCardRepository.
- Then, you are going to specify the entry you want to update by putting the entry’s id, which you can see on the admin dashboard or when retrieving the entry using GraphQL API. The id field will be put inside where.
- In data, place the values you want to update. In this case, you are going to update the address and marriageStatus fields. So, set James’ new address and change his marriage status as well.
- Last but not least, do not forget to define the fields you are updating inside the collection type name, which is idCardRepository in this case.
Query : mutation{ updateIdCardRepository( input: { where: { id: “5eec56af64968132659fb8d8” } data: { address: “Canal Street, Manchester”, marriageStatus: M, } } ){ idCardRepository{ address marriageStatus } }} |
This is James’ current address and marriage status (after) :
Voila! Successfully updated !
CRUD operation : Delete
Actually this action is forbidden in this project but to be more familiar with GraphQL, at least we should know how to remove an entry using GraphQL.
Also, I made a new record with the name, Abe Hiroki.
Here, I have set faceTop field to 5, and I am going to remove it as it is not a required field.
In GraphQL Playground :
Here are some details :
- When creating a record, you use deleteIdCardRepository.
- Then, you are going to specify the entry you want to update by putting the entry’s id, which you can see on the admin dashboard or when retrieving the entry using GraphQL API. The id field will be put inside where.
- Do not forget to define any field that belongs to the record that you are deleting. Even though the field(s) defined inside idCardRepository is not required, it will delete the record, including the items of the record.
Query : mutation{ deleteIdCardRepository( input: { where: { id: “5eed5cb80cafaf0fd507bb15” } } ){ idCardRepository{ faceTop } }} |
If you take a look at the repository, the entry with the name Abe Hiroki is removed.
Thank you for reading this article, have a nice day!