<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Velda Kiara - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Velda Kiara - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 12 Jun 2026 15:55:11 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/VeldaKiara/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ GraphQL Tutorial – How to Query The Rick and Morty API ]]>
                </title>
                <description>
                    <![CDATA[ I enjoy fictional books about greek gods, demigods, the oracle, and prophecies.  I am a huge fan of Rick Riordan's books. I recently came across Apollo's Trials, based on the greek god Apollo.  When I hear any mention of Apollo, my mind goes to the g... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/graphql-queries-for-everyone/</link>
                <guid isPermaLink="false">66ba554e256e9dbeab31aa96</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GraphQL ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Velda Kiara ]]>
                </dc:creator>
                <pubDate>Tue, 30 May 2023 18:07:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/cover-image--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I enjoy fictional books about greek gods, demigods, the oracle, and prophecies. </p>
<p>I am a huge fan of Rick Riordan's books. I recently came across Apollo's Trials, based on the greek god Apollo. </p>
<p>When I hear any mention of Apollo, my mind goes to the greek god who was the god of practically everything – including but not limited to music, poetry, art, prophecy, truth, archery, plague, healing, sun, and light.</p>
<p><a target="_blank" href="https://www.apollo%5BGraphQL%5D(https://graphql.org/).com/tutorials/">Apollo client</a>, just like the god Apollo, can do many things. For example, it lets you fetch and manage data from a <a target="_blank" href="https://graphql.org/">GraphQL</a> API on your client-side application. It is also simple, flexible, and compatible with any data source.</p>
<p>In this article, we will use the Apollo client to fetch data from the <a target="_blank" href="https://rickandmortyapi.com/%5BGraphQL%5D(https://graphql.org/)">Rick and  Morty API</a>, named after the animated TV show with the same name. We will write a <a target="_blank" href="https://www.freecodecamp.org/news/5-ways-to-fetch-data-React-GraphQL/">GraphQL query</a> to fetch the data we need. The data will then be displayed using React.</p>
<p>Before we get started with the project, let's go over the use cases of GraphQL, and how it differs to REST APIs.</p>
<h2 id="heading-what-are-the-use-cases-of-graphql">What Are The Use Cases of GraphQL?</h2>
<p>GraphQL is used to build applications that require real-time data synchronization, like chat applications. It allows developers to fetch necessary data, reducing data transfer over the network, and improving application performance.</p>
<p>Microservices handle specific functionality or feature of the application, which poses a challenge to developers to work with multiple APIs individually. </p>
<p>GraphQL allows developers to create a single API that acts as a gateway to numerous microservices. It also improves performance since one query retrieves various microservices in a single request.</p>
<p>GraphQL provides a self-documenting schema, making it easy for developers to understand the data model and relationships between data. It also eases the process of creating, testing, and maintaining API, reducing time and cost.</p>
<p>Finally, GraphQL provides versioning capabilities to allow the evolution of the API schema without breaking existing clients. Versioning is possible since clients specify the exact data they need, making it easy to add new fields and remove depreciated ones without affecting existing clients.</p>
<h2 id="heading-what-are-the-differences-between-graphql-and-rest-apis">What Are The Differences Between GraphQL and REST APIs?</h2>
<p>With GraphQL, the client sends a query with the data it needs, and the server responds with that data alone. On the other hand, with <a target="_blank" href="https://www.freecodecamp.org/news/build-consume-and-document-a-rest-api/">REST APIs</a>, the client sends a request to an endpoint, and the server responds with all the data/response related to the endpoint.</p>
<p>REST APIs are resource-based, where the endpoints represent data that can be accessed, created, updated, or deleted. On the other hand, GraphQL is graph-based, where each node represents a relationship between objects.</p>
<p>REST APIs, return data in a JSON (JavaScript Object Notation) or XML (Extensible Markup Language) format. At the same time, GraphQL allows the client to specify the data they need and responds with a JSON object matching the query.</p>
<p>GraphQL provides versioning to enable the API's evolution without disrupting the existing clients, while REST APIs create new endpoints for each version.</p>
<p>In some cases, REST APIs, can suffer from over-fetching or under-fetching, where the server may send much or little data. GraphQL accounts for this by allowing clients to request the data they need, thus reducing the amount of data transferred over a network.</p>
<h2 id="heading-project-setup">Project Setup</h2>
<p>Now that you are familiar with what you can do with GraphQL, let's start building the project.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>Fundamentals on <a target="_blank" href="https://react.dev/">React</a></li>
<li>Know about how <a target="_blank" href="https://www.freecodecamp.org/news/how-apis-work/">APIs work</a> and <a target="_blank" href="https://www.freecodecamp.org/news/learn-css-in-this-free-6-hour-video-course/">CSS (Cascading Style Sheets)</a></li>
</ul>
<h3 id="heading-dependencies-installation">Dependencies Installation</h3>
<p>Create a new React App named "rickandmorty".</p>
<pre><code class="lang-js"> npm init [React](https:<span class="hljs-comment">//react.dev/)-app rickandmorty</span>
</code></pre>
<p>or</p>
<pre><code class="lang-js">npx create-[React](https:<span class="hljs-comment">//react.dev/)-app rickandmorty</span>
</code></pre>
<p>Install Apollo Client and GraphQL. The code below installs two dependencies:</p>
<ol>
<li>@apollo/client contains everything you need, like an in-memory cache, local state management, error handling, and a React-based view layer.</li>
<li>GraphQL provides logic for parsing the queries.</li>
</ol>
<pre><code class="lang-js">npm install @apollo/client [GraphQL](https:<span class="hljs-comment">//graphql.org/)</span>
</code></pre>
<h3 id="heading-rick-amp-morty-api-and-apollo-client-setup">Rick &amp; Morty API and Apollo Client Setup</h3>
<p>Once the project is setup, we need to start using it in our files. Next, navigate to  your <code>index.js</code> file using the <code>cd</code> command, and add the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> [React](https:<span class="hljs-comment">//react.dev/)DOM from '[React](https://react.dev/)-dom/client';</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./index.css'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>;
<span class="hljs-keyword">import</span> reportWebVitals <span class="hljs-keyword">from</span> <span class="hljs-string">'./reportWebVitals'</span>;
<span class="hljs-keyword">import</span> { ApolloClient, InMemoryCache, ApolloProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>;

<span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> ApolloClient({
  <span class="hljs-attr">uri</span>: <span class="hljs-string">'https://rickandmortyapi.com/[GraphQL](https://graphql.org/)'</span>,
  <span class="hljs-attr">cache</span>: <span class="hljs-keyword">new</span> InMemoryCache(),
});

<span class="hljs-keyword">const</span> root = [React](https:<span class="hljs-comment">//react.dev/)DOM.createRoot(document.getElementById('root'));</span>
root.render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ApolloProvider</span> <span class="hljs-attr">client</span>=<span class="hljs-string">{client}</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ApolloProvider</span>&gt;</span></span>,
);
</code></pre>
<p>The code above creates an instance of the Apollo client with the URL (Uniform Resource Locator) of the Rick and Morty API GraphQL endpoint. </p>
<p>The App component is wrapped with the Apollo provider component to pass the client to all child components.</p>
<h3 id="heading-query-implementation">Query Implementation</h3>
<p>Now, create a file called <code>characters.js</code> inside the <code>src</code> folder. The file will contain the query and any other functions that you want to add.</p>
<p>Inside the file, add the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { gql } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> GET_CHARACTERS = gql<span class="hljs-string">`
query Characters{
    characters{
      results {
        name
        species
        status
        type
        gender
        origin{name}
        location {name}
        image
      },
    },
  }
`</span>;
</code></pre>
<p>In the code above, we import <code>gql</code> from the <code>@apollo/client</code> to define our query.</p>
<p>We create and export the variable <code>GET_CHARACTERS</code> as a string with capitalized letters. Capitalization is considered a best practice when defining queries in GraphQL. It is also considered a best practice to wrap strings with a template literal.</p>
<p>Objects in Javascript are collections or containers filled with key-value pairs. A key-value pair is referred to as a property.</p>
<p>The query, in our case, searches for the characters in Rick and Morty. It returns an object with the <code>results</code> property, which is an array of character objects. </p>
<p>Each character has properties like name, species, status, type, gender, and image- you can choose what you want to fetch 😉. </p>
<p>The other properties, origin and location, are objects with a name property for each character’s origin and location.</p>
<h4 id="heading-character-function-definition">Character Function Definition</h4>
<p>In the <code>character.js</code> file, add the following code below the <code>GET_CHARACTERS</code> query after modifying it as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useQuery, gql } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>;
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"[React](https://react.dev/)"</span>;
<span class="hljs-keyword">import</span>  { RandomCharacter } <span class="hljs-keyword">from</span> <span class="hljs-string">'./randomcharacters'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> GET_CHARACTERS = gql<span class="hljs-string">`
query Characters($name: String){
    characters ( filter: {name: $name}){
      results {
        name
        species
        status
        type
        gender
        origin{name}
        location {name}
        image
      },
    },
  }
`</span>;

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CharacterList</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [searchTerm, setSearchTerm] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> {loading, error, data }   = useQuery(GET_CHARACTERS, {<span class="hljs-attr">variables</span>: {<span class="hljs-attr">name</span>: searchTerm}});
  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setSearchTerm(event.target.value);
  };
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"search"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"search for Rick and Morty characters..."</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{searchTerm}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"search-input"</span>  /&gt;</span> 
      {loading &amp;&amp; (
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"loader-container"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"loader"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
       )}
      {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> error <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> }
      {data?.characters.results.length === 0 &amp;&amp; (<span class="hljs-tag">&lt;&gt;</span>   <span class="hljs-tag">&lt;<span class="hljs-name">RandomCharacter</span>/&gt;</span> <span class="hljs-tag">&lt;/&gt;</span></span>)}
      {data &amp;&amp; data.characters.results.map(<span class="hljs-function">(<span class="hljs-params">character</span>) =&gt;</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"card"</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{character.name}</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">backgroundImage:</span> `<span class="hljs-attr">url</span>(${<span class="hljs-attr">character.image</span>})`,<span class="hljs-attr">backgroundRepeat:</span> '<span class="hljs-attr">no-repeat</span>'}}&gt;</span> 
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"info"</span>&gt;</span> 
          <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"h3"</span>&gt;</span> {character.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Status: {character.status}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Species: {character.species} <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Type: {character.type}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Gender: {character.gender}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Origin: {character.origin.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Location: {character.location.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span> 
      ))}
    &lt;/div&gt; 
  );
}
</code></pre>
<p>The <code>export function CharacterList()</code> creates a function that is also exported to and can be used by other parts of the code. </p>
<p>The <code>searchTerm</code> variable initializes the search state  to an empty string and creates a function <code>setSearchTerm</code> to update the value. </p>
<p>The <code>useQuery</code> hook from <code>@apollo/client</code> library fetches data from the API. </p>
<p>The query passes <code>GET_CHARACTERS</code>  and a variable named <code>searchTerm</code> which is a variable to hold the character names being searched. </p>
<p>The <code>handleChange</code>   variable sets <code>searchTerm</code> 's value to the input field's current value. The <code>input</code> field is the search bar that the user will use to search the names of the characters they want to view. The state is handled by <code>handleChange</code>.</p>
<p>We also need to account for issues with loading the site, as well as for any bugs that may occur. </p>
<p><code>loading</code> is dynamically rendered with a spinner  if loading is set to <code>True</code>. An error message is displayed if the error is set to <code>True</code>. </p>
<p>When the user is searching for a character that doesn't exist, we want to present a message and an alternate character they can find more information about – this is where the <code>RandomCharacter</code> comes in. We will define this later on. For now, let's keep it as is.</p>
<p>Once we  fetch the data, we map the <code>data.characters.results</code> array to each character's card. </p>
<p>We also want to change the background of the cards to represent the character the information is for. The <code>backgroundImage</code> in the <code>style</code> property handles the dynamic change of the images. The rest of the items are displayed as text on the card.</p>
<h3 id="heading-how-to-display-data">How To Display Data</h3>
<p>Now that we have a function working, we need to view what is being displayed in the browser, and whether we can make queries and get the data we need. </p>
<p>In your <code>App.js</code> file, add the following code:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">textAlign:</span> '<span class="hljs-attr">center</span>' }} &gt;</span>Rick and Morty Characters<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">CharacterList</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
      );
    }
</code></pre><p><code>&lt;CharacterList /&gt;</code> component displays the information about the characters we are getting from the API.</p>
<h3 id="heading-how-to-randomize-the-characters">How to Randomize The Characters</h3>
<p>Remember that we called the <code>RandomCharacter</code> component but we have yet to define it. </p>
<p>Create a file called <code>randomcharacters.js</code> in <code>src</code> and add the following code:</p>
<pre><code><span class="hljs-keyword">import</span> { useQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">"@apollo/client"</span>;
<span class="hljs-keyword">import</span> { gql } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/client'</span>;
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"[React](https://react.dev/)"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> GET_SINGLE_CHARACTER = gql<span class="hljs-string">`
query Character($id: ID!){
    character   (id: $id) {
        name
        species
        status
        type
        gender
        origin{name}
        location {name}
        image
      },
    },
`</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> RandomCharacter = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [randomNumber, setRandomNumber] = useState(<span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">200</span>));
    <span class="hljs-keyword">const</span> { loading, error, data } = useQuery(GET_SINGLE_CHARACTER, {<span class="hljs-attr">variables</span>: {<span class="hljs-attr">id</span>: randomNumber } });


  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"intro"</span> &gt;</span>
         Sorry, we couldn't find that character 😞  
         <span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span>
         How about this one instead? 😉 <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

      {/* {loading &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>} */}
      {loading &amp;&amp; (
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"loader-container"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"loader"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
       )}
      {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> error <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> }
      {data &amp;&amp; (<span class="hljs-tag">&lt;&gt;</span> 
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"card"</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{data.character.name}</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">backgroundImage:</span> `<span class="hljs-attr">url</span>(${<span class="hljs-attr">data.character.image</span>})`,<span class="hljs-attr">backgroundRepeat:</span> '<span class="hljs-attr">no-repeat</span>'}}&gt;</span> 
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"info"</span>&gt;</span> 
          <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"h3"</span>&gt;</span>{data.character.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Status: {data.character.status}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Species: {data.character.species}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Type: {data.character.type}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Gender: {data.character.gender}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Origin: {data.character.origin.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Location: {data.character.location.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/&gt;</span></span>
      )}
    &lt;/div&gt;
  );
};
</code></pre><p>We will replicate the query we created in the <code>characters.js</code> file,  and rename it to <code>GET_SINGLE_CHARACTER</code>.  Instead of looking for names, we will look for <code>ID</code>s. </p>
<p>We look for <code>ID</code>s because they are unique, and we want to randomize the characters that will be picked once a user does not get the character they are looking for.</p>
<p><code>randomNumber</code> initializes state to the <code>Math.floor</code> function which generates a random number between 0 and 199 inclusive, using the <code>Math.random()</code> method and multiplying it by 200. </p>
<p>The <code>Math.floor</code> function rounds the result of the expression to the nearest integer. Every time the <code>randomNumber</code> needs to be updated the  <code>setRandomNumber</code> function takes a new value as its argument and updates the state.</p>
<p>We have a message to alert the user that the character they are looking for is not found, but they can check out a new character. </p>
<p>The loading spinner is also implemented in this component, and the errors are there in case any issues occur. The images and cards are similar to the <code>characters.js</code> format since we want consistency with how everything looks.</p>
<h3 id="heading-how-to-style-the-display">How to Style the Display</h3>
<p>We will use CSS to style how the cards will look, along with the search bar and the general page.</p>
<p>Having defined the functions and components, we will be adding <code>className</code> attributes to what needs to be styled.</p>
<p>Add the following code:</p>
<pre><code class="lang-js">@<span class="hljs-keyword">import</span> url(https:<span class="hljs-comment">//fonts.googleapis.com/css?family=Roboto:400,500,700);</span>
body{
  <span class="hljs-attr">background</span>: navajowhite;
  font-family: Roboto, veranda;
  padding-bottom: <span class="hljs-number">4</span>em;
}
.card{
  <span class="hljs-attr">position</span>: relative;
  width: <span class="hljs-number">22</span>em;
  height: <span class="hljs-number">30</span>em;
  background-size: <span class="hljs-number">22</span>em <span class="hljs-number">30</span>em;
  box-shadow: <span class="hljs-number">3</span>px <span class="hljs-number">3</span>px <span class="hljs-number">20</span>px rgba(<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0.5</span>);
  margin: auto;
  overflow: hidden;
  margin-bottom: <span class="hljs-number">2</span>em;
}
.card *{
  <span class="hljs-attr">position</span>: relative;
  z-index: <span class="hljs-number">2</span>;
}
.card:hover .info{
  <span class="hljs-attr">bottom</span>: <span class="hljs-number">-3</span>em;
  opacity: <span class="hljs-number">1</span>;
  padding: <span class="hljs-number">2</span>px <span class="hljs-number">1</span>px;
  background-color: navajowhite;
}
.info{
  font-family: <span class="hljs-string">'Droid Serif'</span>, serif;
  font-size: <span class="hljs-number">1.2</span>em;
  color: black;

  line-height: <span class="hljs-number">1.1</span>em;
  padding: <span class="hljs-number">0</span> <span class="hljs-number">2</span>em;
  position: relative;
  bottom: <span class="hljs-number">-4</span>em;
  opacity: <span class="hljs-number">0</span>;
  background: transparent;
  transition: opacity <span class="hljs-number">0.3</span>s, bottom <span class="hljs-number">0.3</span>s;
  text-align: center;
}
<span class="hljs-comment">/* search  bar*/</span>
input[type=<span class="hljs-string">"text"</span>] {
  <span class="hljs-attr">border</span>: none;
  border-radius: <span class="hljs-number">10</span>px;
  background-color: #f2f2f2;
  padding: <span class="hljs-number">10</span>px;
  width: <span class="hljs-number">500</span>px;
  margin: <span class="hljs-number">0</span> auto;
  display: block;
  font-size: <span class="hljs-number">16</span>px;
  font-family: <span class="hljs-string">'Roboto'</span>, sans-serif;
  box-shadow: <span class="hljs-number">2</span>px <span class="hljs-number">2</span>px <span class="hljs-number">5</span>px rgba(<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0.2</span>);
  margin-bottom: <span class="hljs-number">2</span>em;
}

input[type=<span class="hljs-string">"text"</span>]::placeholder {
  <span class="hljs-attr">color</span>: #<span class="hljs-number">999</span>;
  font-style: italic;
}
<span class="hljs-comment">/* no result */</span>
.intro{
<span class="hljs-comment">/* width: 10px; */</span>
text-align: center;
margin: <span class="hljs-number">0</span> auto;
color:black;
font-family: <span class="hljs-string">'Droid Serif'</span>, serif;
font-size: <span class="hljs-number">23</span>px;
font-style: italic;
line-height: <span class="hljs-number">20</span>px;
padding-bottom: <span class="hljs-number">15</span>px;
}
<span class="hljs-comment">/* spinner */</span>
.loader-container {
  <span class="hljs-attr">display</span>: flex;
  justify-content: center;
  align-items: center;
  height: <span class="hljs-number">100</span>px;
}

.loader {
  <span class="hljs-attr">border</span>: <span class="hljs-number">8</span>px solid #f3f3f3; 
  border-top: <span class="hljs-number">8</span>px solid black;
  border-radius: <span class="hljs-number">50</span>%;
  width: <span class="hljs-number">50</span>px;
  height: <span class="hljs-number">50</span>px;
  animation: spin <span class="hljs-number">1</span>s linear infinite;
}

@keyframes spin {
  <span class="hljs-number">0</span>% { <span class="hljs-attr">transform</span>: rotate(<span class="hljs-number">0</span>deg); }
  <span class="hljs-number">100</span>% { <span class="hljs-attr">transform</span>: rotate(<span class="hljs-number">360</span>deg); }
}
</code></pre>
<p>Things to note:</p>
<ul>
<li>The class <code>.card</code> represents what the card will look like.</li>
<li>The class <code>.info</code> represents the body text for the characters, such as the species.</li>
<li>The class <code>.intro</code> represents the text that appears if the character is not found.</li>
<li>The class <code>.loader</code> represents the spinner  that shows before the results are displayed.</li>
</ul>
<p>Your website should now look like <a target="_blank" href="https://graphymorty.netlify.app/">this</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned how to use GraphQL queries with React, manage state using the useState hook, and style the different components of the web application.</p>
<p>May your keyboard be swift, your bugs be few, and your fun meter be off the charts as you code away!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Implement Tokenization using JWT and Django Rest Framework ]]>
                </title>
                <description>
                    <![CDATA[ When I was a young girl, we used to have sports competitions like running a hundred meters, relays, swimming, and basketball games.  My strengths were swimming and basketball. I went home with many gifts or, as my school's game master said, a token o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-jwt-and-django-rest-framework-to-get-tokens/</link>
                <guid isPermaLink="false">66ba555237218559f94f2076</guid>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JSON Web Tokens ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JWT ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tokenization ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Velda Kiara ]]>
                </dc:creator>
                <pubDate>Thu, 23 Feb 2023 15:53:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/Purple-Colorful-Tech-22-YouTube-Channel-Art.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When I was a young girl, we used to have sports competitions like running a hundred meters, relays, swimming, and basketball games. </p>
<p>My strengths were swimming and basketball. I went home with many gifts or, as my school's game master said, a <strong>token of appreciation</strong>.</p>
<p>A token is a secure form used to transmit data between two parties. The medals I got from the competitions hold a lot of value for me, and if I gave them to someone else, they would merely be trinkets.</p>
<p>JavaScript Object Notation (JSON) is a format used to present structured data based on JavaScript syntax. We use it to transmit data in web applications by sending the data from the server to the client's display.</p>
<p>JWT (JSON Web Token) is a form of transmitting a JSON object as information between parties. Let's learn more about what JWTs are and how they work.</p>
<h2 id="heading-the-importance-of-jwts">The Importance of JWTs</h2>
<p>JWTs are important for two main reasons:</p>
<p><strong>Authorization</strong>: in our competitions, we had to present our school identification cards for verification before getting our medals. </p>
<p>Our school IDs acted like log in requests in applications. These requests, in apps, contain a JWT that allows users to get permission to access any resources that are accessible with that token.</p>
<p><strong>Information exchange</strong>: my medals were a badge of honor and a way to get a certificate signed and stamped by our games master for legitimacy. </p>
<p>We use JWTs to exchange information in cases where they are signed – for example using public-private key pairs to make sure that the integrity of the information is not compromised since the payload and header are used to compute signatures.</p>
<h2 id="heading-how-do-jwts-work">How Do JWTs Work?</h2>
<p>A JWT is an authorization token that is included in requests. Here's an example of what one looks like:</p>
<pre><code class="lang-python">eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjczNTI3ODMzLCJpYXQiOjE2NzM1Mjc0MzAsImp0aSI6IjNkMGRkMGZiZjA5ZjRmZWU4MTZmMGQyOTQ5OWU3ZmFmIiwidXNlcl9pZCI6IjFmYTBiMGJkLWY4MmMtNDQzNy1iMmViLTMwOTYzMGZkNzQ2NiJ9.-swqFh4MCecycmodQfO8ZmfsDJ3DqoZBsdNzEWhfzhA
</code></pre>
<p>You can get a JWT through logging in with a username and password. In exchange the server returns an access and refresh token in the form of a JWT. The tokens access resources on the server.</p>
<p>The lifetimes of the access and refresh tokens vary since access tokens last for five minutes or less while the refresh tokens can last for 24 hours. But you can customize the timelines of both types of tokens.</p>
<p>If the access token expires, the client uses the refresh token to summon a new access token from the server. Once the refresh token expires, the user must log in again with their username and password to get a new pair of tokens. </p>
<p>It works this way to prevent damage that can occur when a token is compromised and to prevent unauthorized access.</p>
<h3 id="heading-different-parts-of-a-jwt">Different parts of a JWT</h3>
<p>JWTs hold information in three parts, as you can see in the following code blocks:</p>
<pre><code class="lang-python">header.payload.signature
</code></pre>
<pre><code class="lang-python">header = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9F5
payload = eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTQzODI4NDMxLCJqdGkiOiI3ZjU5OTdiNzE1MGQ0NjU3OWRjMmI0OTE2NzA5N2U3YiIsInVsztZXJfaWQiOjF9
signature = Ju70kdcaHKn1Qaz8H42zrOYk0Jx9kIciuhkTn9Xx7vhikY
</code></pre>
<p>The above JWT is encoded using <a target="_blank" href="https://en.wikipedia.org/wiki/Base64">Base64</a>. Once decoded, the information will include something similar to the following parts:</p>
<h4 id="heading-header">Header</h4>
<p>The header contains:</p>
<ul>
<li>type: the specification that the token is a JWT</li>
<li>algorithm: the signing algorithm used to sign said token</li>
</ul>
<p>Algorithms that are used to sign include <a target="_blank" href="https://www.geeksforgeeks.org/rsa-algorithm-cryptography/">RSA</a>, <a target="_blank" href="https://www.geeksforgeeks.org/hmac-algorithm-in-computer-network/">HMAC</a>, or <a target="_blank" href="https://www.n-able.com/blog/sha-256-encryption#:~:text=The%20SHA%2D256%20algorithm%20is,that%20is%20256%20bits%20long.">SHA256</a>. The signatures for the tokens serve two purposes – integrity and authenticity.</p>
<p>An example of a header with the algorithm and type is as shown below:</p>
<pre><code class="lang-python">{
  <span class="hljs-string">"alg"</span>: <span class="hljs-string">"HS256"</span>,
  <span class="hljs-string">"typ"</span>: <span class="hljs-string">"JWT"</span>
}
</code></pre>
<h4 id="heading-payload">Payload</h4>
<p>The payload contains the intended messages which are commonly known as claims and metadata, as well as any other information.</p>
<p>There are three types of claims:</p>
<ol>
<li>Registered claims: they include exp (expiration time), iss (issuer), sub (subject) and aud (audience). They are highly recommended since they provide information on the use and condition of use of the token.</li>
<li>Public claims: these are claims that are unique to avoid collisions with other services that use JWT. </li>
<li>Private claims: these are claims that are used specifically between two parties that understand the meaning and use. Like the example of my medals, my games master and I understood the value.</li>
</ol>
<p>Below is an example of what a payload looks like.</p>
<pre><code class="lang-python">{
  <span class="hljs-string">"token_type"</span>: <span class="hljs-string">"access"</span>,
  <span class="hljs-string">"exp"</span>: <span class="hljs-number">1543828431</span>,
  <span class="hljs-string">"jti"</span>: <span class="hljs-string">"7f5997b7150d46579dc2b49167097e7b"</span>,
  <span class="hljs-string">"user_id"</span>: <span class="hljs-number">4</span>
}
</code></pre>
<ul>
<li><code>token_type</code> is a label that shows what kind of token this is. Case in point, it's an <code>access token</code>.</li>
<li><code>exp</code> stands for expiration. It's the time the token will stop working – in this case the number represents date and time in Unix time.</li>
<li><code>jti</code> stands for <code>JWT ID</code>. It's a unique identifier for this specific token. The ID is used to keep track of which tokens have been used, to prevent use of the same token more than once.</li>
<li><code>user_id</code>:  is an identifier of the user this token belongs to. In this case, the number 4 is the user identification.</li>
</ul>
<h4 id="heading-signature">Signature</h4>
<p>The signature verifies that information is only accessed by authorized people. It is issued by the JWT backend using base64 + payload +SECRET_KEY. </p>
<p>The signature is verified for each request. To validate the signature, you use the SECRET_KEY. Remember the purpose of having it called SECRET_KEY is so that it is secret. </p>
<p>Now let's see how JWTs work in practice with an example.</p>
<h2 id="heading-project-setup">Project Setup</h2>
<p>To illustrate how JWTs work, I will use the <a target="_blank" href="https://django-rest-framework-simplejwt.readthedocs.io/en/latest/">simple JWT</a>, which is a JSON Web Token authentication plugin for Django Rest Framework (DRF). </p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>To follow along, you should have some prior knowledge of HTML files and how to set up a Django project. You should also be familiar with what an API (Application Programming Interface) is. </p>
<p>You will also need to have a Django project already setup. You could name it <code>tokenization</code> also add an app called <code>access</code>. </p>
<p>Once your app and project are set up, you are good to go. </p>
<h3 id="heading-simple-jwt-installation">Simple JWT Installation</h3>
<p>As mentioned, I will be using the <code>simple JWT</code> which provides JWT authentication for the Django Rest Framework (DRF).  </p>
<p>DRF is a third-party package for Django used as a toolkit for building Web API's. It provides a seamless experience while you build, test, debug and maintain RESTful APIs using in Django. </p>
<p>RESTful APIs (Representational State Transfer APIs) are a type of web API that allow communication between different applications over the internet in a fast, reliable, and scalable way.</p>
<p>RESTful APIs are stateless. This means that requests contain information to finalize the request, and the server does not need to remember the history of previous requests.</p>
<p>To install <code>simple JWT</code>, use the command below in your terminal:</p>
<pre><code class="lang-python">pip install djangorestframework_simplejwt
</code></pre>
<h3 id="heading-how-to-set-authentication-to-simple-jwt">How to Set Authentication to Simple JWT</h3>
<p>Go to your project (tokenization), and in the <code>settings.py</code> file, add the following code to configure the REST framework to use simple JWT for authentication:</p>
<pre><code class="lang-python">REST_FRAMEWORK = {
    <span class="hljs-string">'DEFAULT_AUTHENTICATION_CLASSES'</span>: [
        <span class="hljs-string">'rest_framework_simplejwt.authentication.JWTAuthentication'</span>,
    ],
}
</code></pre>
<p>The code above specifies the default authentication class to be used for all API views in the application.</p>
<p><code>DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ]</code> sets the default authentication class to be  <code>JWTAuthentication</code> from the <code>rest_framework_simplejwt</code> package. This means that all API views in the project will use JWT authentication by default.</p>
<h3 id="heading-how-to-define-uniform-resource-locator-patterns">How to Define Uniform Resource Locator Patterns</h3>
<p>In your project (tokenization), create a file (if you have not created one yet) named<br><code>urls.py</code> . Then add the following code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path
<span class="hljs-keyword">from</span> rest_framework_simplejwt <span class="hljs-keyword">import</span> views <span class="hljs-keyword">as</span> jwt_views

urlpatterns = [
    path(<span class="hljs-string">'api/token/'</span>, jwt_views.TokenObtainPairView.as_view(), name=<span class="hljs-string">'token_obtain_pair'</span>),
    path(<span class="hljs-string">'api/token/refresh/'</span>, jwt_views.TokenRefreshView.as_view(), name=<span class="hljs-string">'token_refresh'</span>),
]
</code></pre>
<p>The <code>path</code> function creates a new URL pattern and maps it to the specified view.</p>
<p>The URL (Uniform Resource Locator) path <code>/api/token/</code> is mapped to the view <code>jwt_views.TokenObtainPairView.as_view()</code>. The <code>as_view()</code>method converts the class-based view to a function-based view used in routing. The <code>name</code> parameter makes it easy to refer to the URL pattern in other parts of your code. </p>
<p>We have now created an endpoint for obtaining JWT tokens. If a request is made to the endpoint, <code>TokenObtainPairView</code>, <code>view</code> handles the request and returns a JWT token in the response for authentication.</p>
<h3 id="heading-how-to-customize-the-token-timelines">How to Customize the Token Timelines</h3>
<p>To customize the timeline of the tokens, first add the <code>rest_framework_simplejwt</code> in your installed apps section in the project (tokenization) under the <code>settings.py</code> file. The purpose for adding the <code>rest_framework_simplejwt</code> is for configuration. </p>
<p>To add the timeline we want, we will first create a dictionary called <code>SIMPLE_JWT</code>. Then we'll create variables to hold timelines for the access and refresh token. </p>
<p>The code snippet below shows how to set up the timelines for the tokens:</p>
<pre><code class="lang-python">INSTALLED_APPS = [
    <span class="hljs-comment">#other files</span>
    <span class="hljs-string">'rest_framework_simplejwt'</span>,
]

SIMPLE_JWT = {
    <span class="hljs-string">'ACCESS_TOKEN_LIFETIME'</span>: timedelta(minutes=<span class="hljs-number">5</span>),
    <span class="hljs-string">'REFRESH_TOKEN_LIFETIME'</span>: timedelta(days=<span class="hljs-number">1</span>),
}
</code></pre>
<p>Before you use the <code>timedelta</code> you will need to import it like this: <code>python from datetime import timedelta</code>.</p>
<h3 id="heading-visual-interaction-of-the-api">Visual Interaction of the API</h3>
<p>In this section, we will use the Django Rest Framework web interface to access the endpoints.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-13-at-10.55.14.png" alt="Image" width="600" height="400" loading="lazy">
<em>Testing tokenization</em></p>
<p>The access and refresh tokens are highlighted in red, as shown above. To get the tokens for a user, you need to input the correct password and username for an existing user.</p>
<p> Use a refresh token through this endpoint for an access token: <code>/api/token/refresh/</code> </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-13-at-10.55.53.png" alt="Image" width="600" height="400" loading="lazy">
<em>Refresh token</em></p>
<p>A refresh token gets an access token without the user using their login credentials to extend the user's session. This provides a seamless user experience and improves security by reducing the number of times a user has to key in their credentials.</p>
<h3 id="heading-how-to-add-a-homepage">How to Add a Homepage</h3>
<p>If you want to create a visually appealing interface, you can build a custom homepage to replace the current display of the API endpoints and error messages.</p>
<p>To add a homepage to your Django project, follow these steps:</p>
<ol>
<li>Create a <code>templates</code> folder in your application (access). Then, add a <code>index.html</code> file inside.</li>
<li>Create a <code>static</code> folder in your application (access) and add a <code>img</code> folder inside.</li>
<li>In this case, I wanted to display an image, so I added the <code>me.png</code> in the img folder.</li>
<li>Add the code below to your <code>html</code> file:</li>
</ol>
<pre><code class="lang-html">{% load static %}
<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
        <span class="hljs-selector-tag">body</span> {
            <span class="hljs-attribute">background-image</span>: <span class="hljs-built_in">url</span>(<span class="hljs-string">"{% static 'img/me.png' %}"</span>);
            <span class="hljs-attribute">background-size</span>: cover;
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>You will notice that we needed to add <code>{% load static %}</code> at the top of the file for proper styling and functioning of the site. <code>{% load static %}</code> serves files like stylesheets(CSS), scripts(JS), and images to your HTML templates to provide the user with a seamless experience while viewing your site.</p>
<h3 id="heading-how-to-define-the-url-patterns-for-your-home-page">How to Define the URL Patterns For Your Home Page</h3>
<p>In your app's (access) <code>urls.py</code> file (create one if you do not have it) add this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path
<span class="hljs-keyword">from</span> django.views.generic <span class="hljs-keyword">import</span> TemplateView

app_name=<span class="hljs-string">'access'</span>

urlpatterns=[
path(<span class="hljs-string">''</span>, TemplateView.as_view(template_name=<span class="hljs-string">'home.html'</span>), name=<span class="hljs-string">'home'</span>),

]
</code></pre>
<p>In your project's (tokenization) <code>settings.py</code> file, add the following code so that the static files are served:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Static files settings</span>
STATIC_ROOT = os.path.join(BASE_DIR, <span class="hljs-string">'static'</span>)
STATIC_URL = <span class="hljs-string">'/static/'</span>
STATICFILES_DIRS = [os.path.join(BASE_DIR, <span class="hljs-string">'access/static'</span>)]
</code></pre>
<p>Once you run the server, your home page should be like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-13-at-10.54.54.png" alt="Image" width="600" height="400" loading="lazy">
<em>home page</em></p>
<h2 id="heading-bugs-and-solutions">Bugs and Solutions</h2>
<p>At some point, I may have deleted the <code>migrations</code> file which deleted some of the data I had. This caused the following error <code>django.db.utils.OperationalError: no such table: customUser</code>. </p>
<p>I was able to solve this through running the command <code>python manage.py migrate --run-syncdb</code> . The command syncs tables by looking into tables not created and then creating them.</p>
<p>I also had an issue of using a port that was already being used by a program I had left running and forgotten about. </p>
<p>To close a port you should identify the process using it by running the command <code>lsof -i :&lt;port_number&gt;</code>. This will show you the user using it and PID. To stop the process use <code>kill &lt;PID&gt;</code>. Additionally, you can use <code>sudo kill -9 -u &lt;username&gt; &lt;pid&gt;</code> .</p>
<p>It's good to know that to kill the port you will need administrator permissions. Also, stopping a process can cause data loss or unusual behavior so ensure your data is backed up before doing this.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this tutorial, you have learned how JWTs work, the structure of different tokens, how to use JWT and DRF to get tokens, how to create and serve static files in Django, and how to handle deleting migration files and kill a port.</p>
<p>There is so much you can learn about <a target="_blank" href="https://www.djangoproject.com/">Django</a> and the <a target="_blank" href="https://www.django-rest-framework.org/">Django Rest Framework.</a></p>
<p>The code for this article can be found <a target="_blank" href="https://github.com/VeldaKiara/tokenization">here</a>.</p>
<p>May your keyboard be swift, your bugs be few, and your fun meter be off the charts as you code away!</p>
<p>Thanks for reading my article on how to implement tokenization using JWT and Django Rest Framework. I'm always up for a good chat about coding and tech, so give me a follow on <a target="_blank" href="https://twitter.com/VeldaKiara">Twitter</a> and let's continue the conversation there.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
