From Zero to API Hero: How I Built My First API

Kartikeya Mishra
3 min readSep 30, 2024

--

Have you ever wanted to build your own API but didn’t know where to start? Trust me, I’ve been there. The world of APIs can seem daunting, but once you get the hang of it, it’s like unlocking a new superpower. Today, I’m going to walk you through how I built a simple API from scratch using Python and Flask. Buckle up — it’s going to be an exciting ride!

From Zero to API Hero: How I Built My First API

Why Build an API?

Before diving into the code, let’s talk about why you might want to build an API in the first place. APIs (Application Programming Interfaces) allow different software applications to communicate with each other. Whether you’re developing a mobile app that needs to fetch data from a server or integrating third-party services into your application, APIs are the glue that holds everything together.

Setting Up the Environment

First things first, we need to set up our development environment.

Installing Python and Flask

If you haven’t installed Python yet, you can download it from the official website. Once you have Python installed, open your terminal and install Flask:

pip install Flask

Writing the API Code

Now comes the fun part — coding!

Step 1: Importing the Necessary Libraries

We start by importing Flask and creating an instance of the Flask app.

from flask import Flask, jsonify, request

app = Flask(__name__)

Step 2: Creating a Sample Data Store

For this example, we’ll create a simple in-memory data store — a list of dictionaries.

books = [
{'id': 1, 'title': '1984', 'author': 'George Orwell'},
{'id': 2, 'title': 'To Kill a Mockingbird', 'author': 'Harper Lee'}
]

Step 3: Defining the API Endpoints

Get All Books

Let’s create an endpoint to retrieve all books.

@app.route('/books', methods=['GET'])
def get_books():
return jsonify({'books': books})

Get a Single Book by ID

We can also retrieve a specific book by its ID.

@app.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((item for item in books if item['id'] == book_id), None)
return jsonify({'book': book})

Add a New Book

To add a new book, we’ll create a POST endpoint.

@app.route('/books', metphods=['POST'])
def add_book():
new_book = request.get_json()
books.append(new_book)
return jsonify({'book': new_book}), 201

Update an Existing Book

Let’s add the ability to update a book’s details.

@app.route('/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
updated_book = request.get_json()
for index, book in enumerate(books):
if book['id'] == book_id:
books[index] = updated_book
return jsonify({'book': updated_book})
return jsonify({'message': 'Book not found'}), 404

Delete a Book

Finally, we’ll add a DELETE endpoint.

@app.route('/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
global books
books = [book for book in books if book['id'] != book_id]
return jsonify({'message': 'Book deleted'})

Step 4: Running the Application

At the bottom of your script, add the following code to run the app.

Copy codeif __name__ == '__main__':
app.run(debug=True)

Testing the API

With the API up and running, it’s time to test it out. You can use tools like Postman or curl commands in your terminal.

Example: Getting All Books

curl http://localhost:5000/books

Example: Adding a New Book

curl -X POST -H "Content-Type: application/json" -d '{"id":3,"title":"The Great Gatsby","author":"F. Scott Fitzgerald"}' http://localhost:5000/books

Conclusion

And there you have it — a simple yet functional API built from scratch! Building an API doesn’t have to be overwhelming. With a basic understanding of HTTP methods and a framework like Flask, you’re well on your way to becoming an API hero.

If you found this guide helpful, feel free to connect with me on LinkedIn or follow me on Twitter. For more of my writings, check out my Medium page. If you’d like to support my work, you can buy me a coffee.

--

--

Kartikeya Mishra

All about new technology in fun and easy way so that you can be confident in it and make your own piece of work using this knowledge !