Lets Create a Github App using Github REST API in React.

Using the Github platform to create your next Project Repository or navigating popular Repositories for Studying is a common practice. What if we created an App where we can search for a Github Organization listing Repos for our use & most importantly Create a Repo on our own for a next Project?

Today we will Build a Github App which can use the Flexibility of the Github REST API to create a Repository as well search for a User/Organization & Repositories under them. All of this will be Developed using React & the popular Material UI Library from Google.

Note : The Author assumes you have a Prerequisite knowledge on React basics.

Dependencies required :

Lets Begin :

First create a Project Directory as usual on any desired location. Next open VS Code Editor from the following Directory. Open the Terminal & run the following command.

npx create-react-app Github-API

You can clean up the Code from function App() in App.js file It should be something like this. Note that the Home Component has not been created yet but the Code within next few Minutes will look like this.

Screenshot from VS Code

Following this in your Root project Directory create a Folder named components, where we will build our React Components for Home, Reading the Repositories & Creating Repositories.

Before building our Components paste the following Dependencies in your index.html file inside public folder

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"    integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"    integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"    crossorigin="anonymous"></script>   <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"    integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p"    crossorigin="anonymous"></script>

Also paste the following Font Awesome link alongside

<script src="https://kit.fontawesome.com/f64eb30908.js" crossorigin="anonymous"></script>

Run the Following Commands for Installing some Packages & Libraries.

npm i axiosnpm install @mui/materialnpm i react-router-dom

Now Lets build our 1st Component of the Application, the Read Component

Note : A prior knowledge on Axios would be helpful for making requests on API endpoints.

Create a component name readRepos inside the component Folder we made earlier. Copy the Following Code inside the Read Component.

Now here’s what we did in our Read Component file.

  • Import Material UI Elements like Button, TextField, Grid, Modal, Box which will be required to Style our Component.
  • Made a functional component named Repos.
export const Repos = () => {
return(
)
}
  • Created a Form to get the User/Organization name to fetch the Repositories for a particular user. Here we will use the Material Components like Button, TextField instead of regular HTML Elements to bring the Life out of our App.
  • Since we need to Capture the Form Values that the user enters, we will use the useState React Hook to create stateful variables for our Axios request. In our TextField we have used the onChange event listener to capture our Form values & set the state variable by using the setName function on line 60.
const [name, setName] = useState()const [apidata, setApiData] = useState([])const [loading, setLoading] = useState(false)const [profile, setProfile] = useState([])const [fetch, setFetch] = useState(false)const handleClose = () => setFetch(false)
  • Once the user clicks on the Search Button, we call the handleSearch Function where we make our Axios Request to a Github API endpoint for Searching the Repositories for a given User/Organization. We will make a get Request from axios to the API Endpoint. The ${name} replaces the name that you have entered in your TextField. Axios is a promise based HTTP Client for serving requests to a server or an endpoint url. On success, it returns a response which is usually a JSON object or an Array of Objects. Once the response is returned from the endpoint, we save the data from the response Object into a React state variable named apidata by setting it’s corresponding setApiData() function.
const handleSearch = (event) => {    event.preventDefault()    setLoading(true)    axios.get(`https://api.github.com/users/${name}/repos`)    .then((response) => {        setLoading(false)        setApiData(response.data)        console.log(apidata)       })
}

Here is our output that we will save into the ApiData state variable which will be an Array. We will call the following fields from the response Array we received from our Axios get Request.

To display the Data, we will now use Bootstrap classes to display data in Tabular form. The last column in the Table for each record leads to the link of that following repository. We will make use of Font Awesome external link icon to display a clickable external link to the repository.

Read Repositories.
  • Similarly, we will create a Button to call another API endpoint to get the Profile Info for a Given User/Organization.
const handleProfile = (event) => {    event.preventDefault()    setFetch(true)    axios.get(`https://api.github.com/users/${name}`)    .then((response) => {        setProfile(response.data)        console.log(profile)
})
}

Here to display the Profile Data, we make the most use of Material UI. It provides a good functionality of a Modal box. We have created a Modal Box and styled it using a Styled Component . Here’s how our well Crafted Read Profile Modal Box will Look like :-

Read Profile

Next we Will move to our Create Repository Component.

Create a new component named createRepos similar to the previous one in the components folder. Use the following code in the create component.

Now here’s what we did in our create Component.

  • Created a Material UI form for input fields using TextField & Switch control along with Bootstrap for form Styling to give it a Card look.
  • The Repository Name along with the GitHub Access Token are the required field when creating a GitHub Repository using REST. Rest parameters are optional like Description & Boolean option for Private Repository (default is false).
  • Here as well we will follow the same rule as above, by creating state variables to capture form values.
const [ desc , setDesc] = useState();    
const [ name, setName] = useState();
const [ token, setToken] = useState();
const [ privacy, setPrivacy] = useState(false);
const [ status, setStatus] = useState(false)
  • Until now everything looks fine. But the main catch comes now. When creating a GitHub Repository from the REST API, the API endpoint ensures that only the authorised users who use the App create a Repository. Since the recent GitHub releases have ensured a new feature of Access Tokens instead of Passwords, we won’t be passing any sensitive information like Access Tokens within the Endpoint URL.
  • So unlike the previous request, we will pass headers to this Axios Post request. Here the Authorization method will be a bearer with Access Token. We will also pass the variables in a body document with corresponding values.
const config = {        
headers : { Authorization : `Bearer ${token}` }
}

const body = {
"name" : name,
"description" : desc,
"private" : privacy
}
  • Once the user clicks on the Create Button, we will use the onClick event listener to call a function named handleCreateRepository(). In the Axios request, we will pass the Headers as well as the Body. We have also used the catch mechanism to catch any Errors while creating a Repository (if the Repository of the following name already exists or an Unauthorised user is trying to create a Repository).
const handleCreateRepository = () => {
setStatus(true)
axios.post(`https://api.github.com/user/repos`,
body,
config
).then((response) => {
setStatus(false)
console.log(response)
alert(`Repository Named ${name} is Created Successfully`)
}).catch((e) => {
setStatus(false)
alert(`Error Creating Repository. Repo either Exists or Wrong naming.`)
})
}

Once the user is able to Create a Repository successfully, we can check our GitHub to see if there is a new Repository created or not. Below down you can see the Output :)

  • In the GitHub Repositories, we can see a new Repository named Zaid-Github-API-Testing as a Private one being created. For a Public Repo, simply don’t Toggle the switch in the Input Form. From my previous Repository as well you’ll can see how big of a fan I am to the Material UI because of its Features & Amazing UI animations alongside Colors it Provides. Google really has done a great deal to the Developers Community.

Now almost everything is Created well. The only thing we are left with is Routing between the Components.

For this last part, Create a home component in the components folder. Use the following code in the Home component.

  • Now in the above code, we have used BrowserRouter, Link & Route to use Routing.
  • Material UI provides a really good UI element for Navbar called as AppBar. We will use AppBar along with Toolbar to create a Blue navigation.
  • We have also created Buttons to Route between the Components. Here’s how we did it.
<div className="mx-3">                                
<Link to="/create" className="text-decoration-none">
<Button variant="contained" size="large">
<i className="fas fa-plus mx-2"></i>
Create Repository
</Button>
</Link>
</div>
<div className="mx-3">
<Link to="/read" className="text-decoration-none">
<Button variant="contained" size="large">
<i className="fas fa-bookmark mx-2"></i>
Read Repositories
</Button>
</Link>
</div>

Also not to Forget to Add the Route paths below at the end.

<Route path="/create" component={Create} exact />
<Route path="/read" component={Repos} exact />

At the end, we should import all the Modules in their respective Files and call the <Home/> component in the App.js file.

Before finishing the Project, let’s add some custom CSS for our Forms that we wrote. Paste the Following in the App.css file

.profile_url{border-radius: 50%;}.custom-profile{margin : 5px 35%;}.crud-form{width: 40%;margin: 0 30%;box-sizing: border-box;border: 1px solid #fff;border-radius: 10px;box-shadow: 2px 2px 6px 0 #c7cdea;}.terms{font-size: 14px;font-family: sans-serif;}.crud-form-field{margin: 1rem;padding: .2rem;font-family:'Courier New', Courier, monospace;}.nav i{font-size: 2rem;}.custom-nav{float : right;display : flex;}

With this, we complete our Simple GitHub App that we can leverage for our Development usage.

One thing I’d like to share is that there are more features to Add to this GitHub Application like GitHub Actions, Tracking Issues, Creating Issues, Fetching Commit History & Collaborations all using the GitHub REST API. Feel free to reach out for Improving this Project.

GitHub Link :- https://github.com/Zaid-Shaikh333/GithubApp

If you liked this Story & this Project do give it a Clap 👏 there 👇. I’ll come up with more such Tech Articles in Future.

LinkedIn :- https://www.linkedin.com/in/zaid-shaikh-10a286194

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store