How to Use APIs in Python
What is an API?
APIs enable seamless communication between software applications, whether for checking the weather, booking a ride, or making secure online payments.
An API (Application Programming Interface) serves as a bridge that facilitates communication between different software systems. In modern software development, APIs seamlessly exchange data and functionality in applications, services, and devices. Whether retrieving weather updates, processing payments, or streaming content, APIs establish rules for making requests and receiving responses, ensuring seamless communication between software components.
At its core, an API provides a structured way for programs to interact without needing direct access to each other’s internal logic. It abstracts complexity, offering a set of rules and protocols that dictate how software components should interact—just like a restaurant menu allows diners to request meals without knowing the kitchen’s inner workings.
API Development with Swagger and OpenAPI
Learn how to develop APIs using Swagger tooling and the OpenAPI specification.Try it for freeTypes of APIs
APIs can be categorized based on their architecture and communication style:
REST (Representational State Transfer): The most common type for web-based communication. REST APIs follow standard HTTP methods and return data, often in JSON format.
SOAP (Simple Object Access Protocol): A protocol-based API that uses XML for structured communication, often employed in enterprise applications.
GraphQL: A query language for APIs that enables clients to specify the exact data they require, reducing over-fetching and improving efficiency compared to REST.
WebSockets: These enable real-time, two-way communication between clients and servers. They are often used in chat applications and live updates.
In this article, we will primarily focus on REST APIs, which are simple, efficient, and widely adopted in web development.
With an understanding of APIs, let’s explore an API’s basic elements.
Understanding the basics of an API
APIs function as messengers between different software systems. When an application needs data or functionality from another system, it sends a request, which the API processes and returns a response. This interaction follows a structured format, ensuring seamless communication between applications.
Key components of an API
- Endpoints: These are specific URLs where APIs receive requests.
- Request Methods: Specify the action a system has to perform, such as retrieving data or submitting information.
- Responses: Data returned by the API, often in JSON (JavaScript Object Notation) format, which is easy for humans and machines to read.
APIs follow a request-response pattern in which a client, such as a web or mobile application, sends a request to a designated API endpoint. The server then processes this request and delivers a structured response.
With these basics covered, let’s explore the HTTP methods crucial in working with APIs.
Understanding HTTP methods in APIs
When an app creates or updates data, how does the information get sent or retrieved? HTTP methods handle this process!
HTTP methods define the type of action an API request performs. The most common methods include:
- GET – Retrieve Data: Used to fetch information from the server, like retrieving a list of users.
- POST – Create Data: Sends new data to the server, such as adding a new user.
- PUT – Update Data: Modifies an existing resource, like updating a user’s profile.
- DELETE – Remove Data: Deletes a resource, such as removing a user from a database.
Each method ensures a structured way to manage resources within an API.
Now that HTTP methods are clear let’s explore HTTP status codes, which inform clients about the success or failure of their requests.
Decoding HTTP Status Codes in APIs
APIs provide feedback on requests through HTTP status codes —three-digit numbers that indicate whether a request was successful, failed, or encountered an issue.
Some key status codes include:
- 200 OK – Success: The request was processed successfully, and the server provided the expected response.
- 201 Created – Resource Added: A new resource, such as a newly registered user, was successfully created.
- 400 Bad Request – Invalid Input: The request was malformed or contained incorrect data.
- 404 Not Found – Missing Resource: The requested resource does not exist.
- 500 Internal Server Error – Server Issue: The server encountered an unexpected problem.
By understanding these status codes, clients can determine how to respond—whether to show a success message, prompt a retry, or notify users of an error.
With a solid grasp of HTTP methods and status codes, it’s time to start building APIs in Python.
How to create APIs in Python?
What if there was a way to create APIs in Python with just a few lines of code? FastAPI is a modern, high-performance framework designed for building APIs quickly and efficiently.
Python offers several frameworks for API development, including Flask and Django REST Framework. However, FastAPI stands out due to its speed, built-in type validation, automatic documentation, and support for asynchronous programming. Its design makes API development more efficient while maintaining simplicity.
Before setting up an API, it’s essential to understand why FastAPI is a preferred choice.
What is FastAPI
FastAPI is a web framework optimized for building APIs with minimal effort. It leverages Python type hints to provide robust validation and automatic API documentation, making development faster and more reliable.
Key Features of FastAPI
- Automatic API Documentation – Generates interactive documentation using Swagger UI and Redoc.
- Type Validation – Ensures data correctness with Python’s type hints.
- Asynchronous Support – Efficiently handles multiple requests using async and await.
- High Performance – Built on Starlette and Pydantic, making it as fast as Node.js frameworks.
One of the most useful features of FastAPI is the automatic API documentation, which generates a fully interactive interface without requiring additional configuration.
Next, let’s set up FastAPI by installing the necessary dependencies and creating a basic application.
Setting Up FastAPI
FastAPI requires installation along with Uvicorn, a lightweight ASGI server that runs applications efficiently.
Using a virtual environment is recommended to keep dependencies isolated.
Step 1: Set Up a Virtual Environment
Create and activate a virtual environment before installing dependencies:
# Create a virtual environmentpython -m venv venv# Activate the virtual environment# On Windowsvenv\Scripts\activate# On macOS/Linuxsource venv/bin/activate
Step 2: Install FastAPI and Uvicorn
Run the following command to install both dependencies:
pip install fastapi uvicorn
Step 3: Create a Basic FastAPI Application
Create a new Python file (main.py
) and add the following code:
from fastapi import FastAPIapp = FastAPI()@app.get("/")def read_root():return {"message": "Hello, World!"}
Step 4: Run the Application
Use Uvicorn to start the FastAPI server:
uvicorn main:app --reload
This command starts the server, making the API accessible at http://127.0.0.1:8000
. After running the command, the terminal will display output similar to:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)INFO: Started reloader process [...]INFO: Application startup complete.
Step 5: Access the API
Open a browser and visit http://127.0.0.1:8000
. The webpage will display a message like this -
{"message": "Hello, World!"}
FastAPI also provides built-in interactive documentation, which is directly accessible in the browser at the /docs
and /redoc
endpoints:
- Swagger UI: http://127.0.0.1:8000/docs
- ReDoc: http://127.0.0.1:8000/redoc
This confirms that our FastAPI setup is complete and working fine. The next step is to create API endpoints, starting with a GET request.
Creating a GET API Endpoint
How would an application retrieve user information from a database? A GET
API endpoint handles this task.
In FastAPI, a GET
request retrieves data from the server. The @app.get
decorator makes it easy to define such endpoints. Below is an example of a simple GET
endpoint that returns a list of users:
from fastapi import FastAPIapp = FastAPI()users = [{"id": 1, "name": "Alice"},{"id": 2, "name": "Bob"},]@app.get("/users")def get_users():return users
Explanation
- The
@app.get("/users")
decorator defines aGET
endpoint at/users
. - The
get_users
function returns a list of user objects.
Running the API
Start the FastAPI server using:
uvicorn main:app --reload
Access the endpoint by visiting http://127.0.0.1:8000/users
in a browser or API testing tool.
With the GET
endpoint in place, the next step is to create a POST
endpoint for handling data submissions.
Creating a POST
API Endpoint
Retrieving data is essential, but applications often need to accept and store new data. A POST API endpoint allows clients to send data to the server.
FastAPI simplifies this process using the @app.post
decorator and request body validation. Here’s an example that allows users to submit new entries:
from fastapi import FastAPIfrom pydantic import BaseModelapp = FastAPI()users = []class User(BaseModel):id: intname: str@app.post("/users")def create_user(user: User):users.append(user.dict())return {"message": "User added successfully", "user": user}
Explanation
- The
User
class ensures incoming data follows the correct format. - The
@app.post("/users")
decorator defines aPOST
endpoint. - The
create_user
function accepts JSON data and adds it to the users list.
Testing the API
To test the API, we will send a POST
request to http://127.0.0.1:8000/users
with the following JSON body:
{"id": 3,"name": "Charlie"}
The server returns a confirmation message along with the newly added user details.
With GET
and POST
endpoints in place, the fundamentals of retrieving and submitting data in FastAPI are now covered.
Conclusion
APIs enable modern software to communicate seamlessly. This article explained the basics of Python API, key HTTP concepts, and how to build a simple API using FastAPI. We walked through setting up FastAPI and creating GET
and POST
endpoints, laying the groundwork for API development.
With these basics covered, the next step is to apply this knowledge by building real-world projects. Implementing additional features such as PUT and DELETE requests, authentication, and deployment will provide a deeper understanding and improve API development skills.
For more hands-on learning, explore Learn APIs with Codecademy for a comprehensive introduction to API concepts and best practices.
To further enhance your knowledge of API design, documentation, and testing, explore API Development with Swagger and OpenAPI course from Codecademy.
Author
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
How to Request Webpages Using Python
Learn how to request webpages and get JSON data using Python's requests library. A step-by-step guide with practical examples for making HTTP GET and POST requests in Python. - Article
Creating an OpenAI API Key
Learn how to create and use a ChatGPT API key. - Article
Back-End Web Architecture
This article provides an overview of servers, databases, routing, and anything else that happens between when a client makes a request and receives a response.
Learn more on Codecademy
- Course
API Development with Swagger and OpenAPI
Learn how to develop APIs using Swagger tooling and the OpenAPI specification.With CertificateIntermediate< 1 hour - Free course
Intro to OpenAI API
Explore OpenAI’s API and learn how to write more effective generative AI prompts that help improve your results.Beginner Friendly< 1 hour - Free course
Using OpenAI APIs: Accessing OpenAI APIs from Python
Excel in OpenAI APIs using Python. Discover API key authentication, access to completions APIs via endpoints, model configurations, and control of creativity and response length.Beginner Friendly2 hours