DEV Community

Roy for BLST

Posted on

Building an API using FastAPI and Uvicorn

Building APIs is a crucial aspect of modern software development, and FastAPI is a popular Python web framework that makes it easier than ever to build high-performance APIs. With its automatic data validation, serialization, and documentation, FastAPI can help developers save time and build robust APIs. In addition, Uvicorn, a lightning-fast ASGI server, can provide high concurrency and great performance for running Python web applications.

Install Required Libraries

To start building our API, we'll need to install FastAPI and Uvicorn using the pip install command.

pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

Define the API Endpoints

FastAPI provides a simple and intuitive syntax for defining API endpoints. We can define our endpoints in a single Python file using FastAPI's 'FastAPI' class and decorators for HTTP methods. Here's an example:

from fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
def hello(name: str = ""):
    return {"message": f"Hello {name}"}
Enter fullscreen mode Exit fullscreen mode

This code defines endpoint '/hello' that responds to GET requests with JSON data that has a 'message' key.

Run the API

To run the API, we can use Uvicorn to start a development server:

import uvicorn

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
Enter fullscreen mode Exit fullscreen mode

This code starts a development server on port 8000 that listens for incoming requests. You can the server by running the Python file.

Test the API

We can test the API using any HTTP client, such as 'curl', 'request', or a web browser. For example, to test the '/hello' endpoint, we can use our command line and run:

curl http://localhost:8000/hello?name=john
Enter fullscreen mode Exit fullscreen mode

This will return the JSON object we defined earlier, It will look like this: {"message": "Hello john"}.

And that's it! You have successfully built your first running endpoint on your API using Python, now all that is left is to add as many endpoints as you want.
You can define endpoints for different types of requests such as GET, POST, PUT, DELETE, etc. each with its own set of functionalities.

Join the discussion in our Discord channel
Test your API for free now at BLST!

Oldest comments (0)